zoukankan      html  css  js  c++  java
  • React Native 的ES5 ES6写法对照表

    模块

    引用

    在ES5里,如果使用CommonJS标准,引入React包基本通过require进行,代码类似这样:

     1 //ES5
     2 var React = require("react");
     3 var {
     4     Component,
     5     PropTypes
     6 } = React;  //引用React抽象组件
     7 
     8 var ReactNative = require("react-native");
     9 var {
    10     Image,
    11     Text,
    12 } = ReactNative;  //引用具体的React Native组件

    在ES6里,import写法更为标准

    1 //ES6
    2 import React, { 
    3     Component,
    4     PropTypes,
    5 } from 'react';
    6 import {
    7     Image,
    8     Text
    9 } from 'react-native'

    注意在React Native里,import直到0.12+才能正常运作。

    导出单个类

    在ES5里,要导出一个类给别的模块用,一般通过module.exports来导出

    1 //ES5
    2 var MyComponent = React.createClass({
    3     ...
    4 });
    5 module.exports = MyComponent;

    在ES6里,通常用export default来实现相同的功能:

    1 //ES6
    2 export default class MyComponent extends Component{
    3     ...
    4 }

    引用的时候也类似:

    1 //ES5
    2 var MyComponent = require('./MyComponent');
    3 
    4 //ES6
    5 import MyComponent from './MyComponent';

    定义组件

    在ES5里,通常通过React.createClass来定义一个组件类,像这样:

    1 //ES5
    2 var Photo = React.createClass({
    3     render: function() {
    4         return (
    5             <Image source={this.props.source} />
    6         );
    7     },
    8 });

    在ES6里,我们通过定义一个继承自React.Component的class来定义一个组件类,像这样:

    1 //ES6
    2 class Photo extends React.Component {
    3     render() {
    4         return (
    5             <Image source={this.props.source} />
    6         );
    7     }
    8 }

    给组件定义方法

    从上面的例子里可以看到,给组件定义方法不再用 名字: function()的写法,而是直接用名字(),在方法的最后也不能有逗号了。

     1 //ES5 
     2 var Photo = React.createClass({
     3     componentWillMount: function(){
     4 
     5     },
     6     render: function() {
     7         return (
     8             <Image source={this.props.source} />
     9         );
    10     },
    11 });
     1 //ES6
     2 class Photo extends React.Component {
     3     componentWillMount() {
     4 
     5     }
     6     render() {
     7         return (
     8             <Image source={this.props.source} />
     9         );
    10     }
    11 }

    定义组件的属性类型和默认属性

    在ES5里,属性类型和默认属性分别通过propTypes成员和getDefaultProps方法来实现

     1 //ES5 
     2 var Video = React.createClass({
     3     getDefaultProps: function() {
     4         return {
     5             autoPlay: false,
     6             maxLoops: 10,
     7         };
     8     },
     9     propTypes: {
    10         autoPlay: React.PropTypes.bool.isRequired,
    11         maxLoops: React.PropTypes.number.isRequired,
    12         posterFrameSrc: React.PropTypes.string.isRequired,
    13         videoSrc: React.PropTypes.string.isRequired,
    14     },
    15     render: function() {
    16         return (
    17             <View />
    18         );
    19     },
    20 });

    在ES6里,可以统一使用static成员来实现

     1 //ES6
     2 class Video extends React.Component {
     3     static defaultProps = {
     4         autoPlay: false,
     5         maxLoops: 10,
     6     };  // 注意这里有分号
     7     static propTypes = {
     8         autoPlay: React.PropTypes.bool.isRequired,
     9         maxLoops: React.PropTypes.number.isRequired,
    10         posterFrameSrc: React.PropTypes.string.isRequired,
    11         videoSrc: React.PropTypes.string.isRequired,
    12     };  // 注意这里有分号
    13     render() {
    14         return (
    15             <View />
    16         );
    17     } // 注意这里既没有分号也没有逗号
    18 }

    也有人这么写,虽然不推荐,但读到代码的时候你应当能明白它的意思:

     1 //ES6
     2 class Video extends React.Component {
     3     render() {
     4         return (
     5             <View />
     6         );
     7     }
     8 }
     9 Video.defaultProps = {
    10     autoPlay: false,
    11     maxLoops: 10,
    12 };
    13 Video.propTypes = {
    14     autoPlay: React.PropTypes.bool.isRequired,
    15     maxLoops: React.PropTypes.number.isRequired,
    16     posterFrameSrc: React.PropTypes.string.isRequired,
    17     videoSrc: React.PropTypes.string.isRequired,
    18 };

    注意: 对React开发者而言,static成员在IE10及之前版本不能被继承,而在IE11和其它浏览器上可以,这有时候会带来一些问题。React Native开发者可以不用担心这个问题。

    初始化state

    ES5下情况类似,

    1 //ES5 
    2 var Video = React.createClass({
    3     getInitialState: function() {
    4         return {
    5             loopsRemaining: this.props.maxLoops,
    6         };
    7     },
    8 })

    ES6下,有两种写法:

    1 //ES6
    2 class Video extends React.Component {
    3     state = {
    4         loopsRemaining: this.props.maxLoops,
    5     }
    6 }

    不过我们推荐更易理解的在构造函数中初始化(这样你还可以根据需要做一些计算):

    1 //ES6
    2 class Video extends React.Component {
    3     constructor(props){
    4         super(props);
    5         this.state = {
    6             loopsRemaining: this.props.maxLoops,
    7         };
    8     }
    9 }

    把方法作为回调提供

    很多习惯于ES6的用户反而不理解在ES5下可以这么做:

     1 //ES5
     2 var PostInfo = React.createClass({
     3     handleOptionsButtonClick: function(e) {
     4         // Here, 'this' refers to the component instance.
     5         this.setState({showOptionsModal: true});
     6     },
     7     render: function(){
     8         return (
     9             <TouchableHighlight onPress={this.handleOptionsButtonClick}>
    10                 <Text>{this.props.label}</Text>
    11             </TouchableHighlight>
    12         )
    13     },
    14 });

    在ES5下,React.createClass会把所有的方法都bind一遍,这样可以提交到任意的地方作为回调函数,而this不会变化。但官方现在逐步认为这反而是不标准、不易理解的。

    在ES6下,你需要通过bind来绑定this引用,或者使用箭头函数(它会绑定当前scope的this引用)来调用

     1 //ES6
     2 class PostInfo extends React.Component
     3 {
     4     handleOptionsButtonClick(e){
     5         this.setState({showOptionsModal: true});
     6     }
     7     render(){
     8         return (
     9             <TouchableHighlight 
    10                 onPress={this.handleOptionsButtonClick.bind(this)}
    11                 onPress={e=>this.handleOptionsButtonClick(e)}
    12                 >
    13                 <Text>{this.props.label}</Text>
    14             </TouchableHighlight>
    15         )
    16     },
    17 }

    箭头函数实际上是在这里定义了一个临时的函数,箭头函数的箭头=>之前是一个空括号、单个的参数名、或用括号括起的多个参数名,而箭头之后可以是一个表达式(作为函数的返回值),或者是用花括号括起的函数体(需要自行通过return来返回值,否则返回的是undefined)。

     1 // 箭头函数的例子
     2 ()=>1
     3 v=>v+1
     4 (a,b)=>a+b
     5 ()=>{
     6     alert("foo");
     7 }
     8 e=>{
     9     if (e == 0){
    10         return 0;
    11     }
    12     return 1000/e;
    13 }

    需要注意的是,不论是bind还是箭头函数,每次被执行都返回的是一个新的函数引用,因此如果你还需要函数的引用去做一些别的事情(譬如卸载监听器),那么你必须自己保存这个引用

     1 // 错误的做法
     2 class PauseMenu extends React.Component{
     3     componentWillMount(){
     4         AppStateIOS.addEventListener('change', this.onAppPaused.bind(this));
     5     }
     6     componentDidUnmount(){
     7         AppStateIOS.removeEventListener('change', this.onAppPaused.bind(this));
     8     }
     9     onAppPaused(event){
    10     }
    11 }
     1 // 正确的做法
     2 class PauseMenu extends React.Component{
     3     constructor(props){
     4         super(props);
     5         this._onAppPaused = this.onAppPaused.bind(this);
     6     }
     7     componentWillMount(){
     8         AppStateIOS.addEventListener('change', this._onAppPaused);
     9     }
    10     componentDidUnmount(){
    11         AppStateIOS.removeEventListener('change', this._onAppPaused);
    12     }
    13     onAppPaused(event){
    14     }
    15 }

    这个帖子中我们还学习到一种新的做法:

     1 // 正确的做法
     2 class PauseMenu extends React.Component{
     3     componentWillMount(){
     4         AppStateIOS.addEventListener('change', this.onAppPaused);
     5     }
     6     componentDidUnmount(){
     7         AppStateIOS.removeEventListener('change', this.onAppPaused);
     8     }
     9     onAppPaused = (event) => {
    10         //把方法直接作为一个arrow function的属性来定义,初始化的时候就绑定好了this指针
    11     }
    12 }

    Mixins

    在ES5下,我们经常使用mixin来为我们的类添加一些新的方法,譬如PureRenderMixin

    1 var PureRenderMixin = require('react-addons-pure-render-mixin');
    2 React.createClass({
    3   mixins: [PureRenderMixin],
    4 
    5   render: function() {
    6     return <div className={this.props.className}>foo</div>;
    7   }
    8 });

    然而现在官方已经不再打算在ES6里继续推行Mixin,他们说:Mixins Are Dead. Long Live Composition

    尽管如果要继续使用mixin,还是有一些第三方的方案可以用,譬如这个方案

    不过官方推荐,对于库编写者而言,应当尽快放弃Mixin的编写方式,上文中提到Sebastian Markbåge的一段代码推荐了一种新的编码方式:

     1 //Enhance.js
     2 import { Component } from "React";
     3 
     4 export var Enhance = ComposedComponent => class extends Component {
     5     constructor() {
     6         this.state = { data: null };
     7     }
     8     componentDidMount() {
     9         this.setState({ data: 'Hello' });
    10     }
    11     render() {
    12         return <ComposedComponent {...this.props} data={this.state.data} />;
    13     }
    14 };
    15 //HigherOrderComponent.js
    16 import { Enhance } from "./Enhance";
    17 
    18 class MyComponent {
    19     render() {
    20         if (!this.data) return <div>Waiting...</div>;
    21         return <div>{this.data}</div>;
    22     }
    23 }
    24 
    25 export default Enhance(MyComponent); // Enhanced component

    用一个“增强函数”,来某个类增加一些方法,并且返回一个新类,这无疑能实现mixin所实现的大部分需求。

    ES6+带来的其它好处

    解构&属性延展

    结合使用ES6+的解构和属性延展,我们给孩子传递一批属性更为方便了。这个例子把className以外的所有属性传递给div标签:

     1 class AutoloadingPostsGrid extends React.Component {
     2     render() {
     3         var {
     4             className,
     5             ...others,  // contains all properties of this.props except for className
     6         } = this.props;
     7         return (
     8             <div className={className}>
     9                 <PostsGrid {...others} />
    10                 <button onClick={this.handleLoadMoreClick}>Load more</button>
    11             </div>
    12         );
    13     }
    14 }

    下面这种写法,则是传递所有属性的同时,用覆盖新的className值:

    1 <div {...this.props} className="override">
    2 3 </div>

    这个例子则相反,如果属性中没有包含className,则提供默认的值,而如果属性中已经包含了,则使用属性中的值

    1 <div className="base" {...this.props}>
    2 3 </div>

    原文转载自:  React Native中文网

  • 相关阅读:
    NOIP2016——组合数问题
    BZOJ3450——Tyvj1952(OSU?)
    洛谷4316——绿豆蛙的归宿(期望)
    BZOJ1997——次小生成树(严格次小生成树)
    USACO2002-OPEN-GREEN(GREEN秘密的牛奶管道SECRET)
    Linux系统应急响应
    Linux系统登录相关
    (翻译)Attacking Interoperability(攻击互操作性)in Black Hat 2009 研究报告
    HTTP参数污染(HPP)漏洞
    逻辑漏洞之越权访问漏洞
  • 原文地址:https://www.cnblogs.com/shaoting/p/6108382.html
Copyright © 2011-2022 走看看