React/React Native 的ES5 ES6寫(xiě)法對(duì)照表

很多React/React Native的初學(xué)者都被ES6的問(wèn)題迷惑:各路大神都建議我們直接學(xué)習(xí)ES6的語(yǔ)法(class Foo extends React.Component),然而網(wǎng)上搜到的很多教程和例子都是ES5版本的,所以很多人在學(xué)習(xí)的時(shí)候連照貓畫(huà)虎都不知道怎么做。今天在此整理了一些ES5和ES6的寫(xiě)法對(duì)照表,希望大家以后讀到ES5的代碼,也能通過(guò)對(duì)照,在ES6下實(shí)現(xiàn)相同的功能。

模塊

引用

在ES5里,如果使用CommonJS標(biāo)準(zhǔn),引入React包基本通過(guò)require進(jìn)行,代碼類(lèi)似這樣:

//ES5
var React = require("react");
var {
    Component,
    PropTypes
} = React;  //引用React抽象組件

var ReactNative = require("react-native");
var {
    Image,
    Text,
} = ReactNative;  //引用具體的React Native組件

在ES6里,import寫(xiě)法更為標(biāo)準(zhǔn)

//ES6
import React, { 
    Component,
    PropTypes,
} from 'react';
import {
    Image,
    Text
} from 'react-native'

導(dǎo)出單個(gè)類(lèi)

在ES5里,要導(dǎo)出一個(gè)類(lèi)給別的模塊用,一般通過(guò)module.exports來(lái)導(dǎo)出

//ES5
var MyComponent = React.createClass({
    ...
});
module.exports = MyComponent;

在ES6里,通常用export default來(lái)實(shí)現(xiàn)相同的功能:

//ES6
export default class MyComponent extends Component{
    ...
}

引用的時(shí)候也類(lèi)似:

//ES5
var MyComponent = require('./MyComponent');

//ES6
import MyComponent from './MyComponent';

注意導(dǎo)入和導(dǎo)出的寫(xiě)法必須配套,不能混用!

定義組件

在ES5里,通常通過(guò)React.createClass來(lái)定義一個(gè)組件類(lèi),像這樣:

//ES5
var Photo = React.createClass({
    render: function() {
        return (
            <Image source={this.props.source} />
        );
    },
});

在ES6里,我們通過(guò)定義一個(gè)繼承自React.Component的class來(lái)定義一個(gè)組件類(lèi),像這樣:

//ES6
class Photo extends React.Component {
    render() {
        return (
            <Image source={this.props.source} />
        );
    }
}

給組件定義方法

從上面的例子里可以看到,給組件定義方法不再用 名字: function()的寫(xiě)法,而是直接用 名字() ,在方法的最后也不能有逗號(hào)了。

//ES5 
var Photo = React.createClass({
    componentWillMount: function(){

    },
    render: function() {
        return (
            <Image source={this.props.source} />
        );
    },
});
//ES6
class Photo extends React.Component {
    componentWillMount() {

    }
    render() {
        return (
            <Image source={this.props.source} />
        );
    }
}

定義組件的屬性類(lèi)型和默認(rèn)屬性

在ES5里,屬性類(lèi)型和默認(rèn)屬性分別通過(guò)propTypes成員和getDefaultProps方法來(lái)實(shí)現(xiàn)

//ES5 
var Video = React.createClass({
    getDefaultProps: function() {
        return {
            autoPlay: false,
            maxLoops: 10,
        };
    },
    propTypes: {
        autoPlay: React.PropTypes.bool.isRequired,
        maxLoops: React.PropTypes.number.isRequired,
        posterFrameSrc: React.PropTypes.string.isRequired,
        videoSrc: React.PropTypes.string.isRequired,
    },
    render: function() {
        return (
            <View />
        );
    },
});

在ES6里,可以統(tǒng)一使用static成員來(lái)實(shí)現(xiàn)

//ES6
class Video extends React.Component {
    static defaultProps = {
        autoPlay: false,
        maxLoops: 10,
    };  // 注意這里有分號(hào)
    static propTypes = {
        autoPlay: React.PropTypes.bool.isRequired,
        maxLoops: React.PropTypes.number.isRequired,
        posterFrameSrc: React.PropTypes.string.isRequired,
        videoSrc: React.PropTypes.string.isRequired,
    };  // 注意這里有分號(hào)
    render() {
        return (
            <View />
        );
    } // 注意這里既沒(méi)有分號(hào)也沒(méi)有逗號(hào)
}

也有人這么寫(xiě),雖然不推薦,但讀到代碼的時(shí)候你應(yīng)當(dāng)能明白它的意思:

//ES6
class Video extends React.Component {
    render() {
        return (
            <View />
        );
    }
}
Video.defaultProps = {
    autoPlay: false,
    maxLoops: 10,
};
Video.propTypes = {
    autoPlay: React.PropTypes.bool.isRequired,
    maxLoops: React.PropTypes.number.isRequired,
    posterFrameSrc: React.PropTypes.string.isRequired,
    videoSrc: React.PropTypes.string.isRequired,
};

注意: 對(duì)React開(kāi)發(fā)者而言,static成員在IE10及之前版本不能被繼承,而在IE11和其它瀏覽器上可以,這有時(shí)候會(huì)帶來(lái)一些問(wèn)題。React Native開(kāi)發(fā)者可以不用擔(dān)心這個(gè)問(wèn)題。

初始化state

ES5下情況類(lèi)似,

//ES5 
var Video = React.createClass({
    getInitialState: function() {
        return {
            loopsRemaining: this.props.maxLoops,
        };
    },
})

ES6下,有兩種寫(xiě)法:

//ES6
class Video extends React.Component {
    state = {
        loopsRemaining: this.props.maxLoops,
    }
}

不過(guò)我們推薦更易理解的在構(gòu)造函數(shù)中初始化(這樣你還可以根據(jù)需要做一些計(jì)算):

//ES6
class Video extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            loopsRemaining: this.props.maxLoops,
        };
    }
}

把方法作為回調(diào)提供

很多習(xí)慣于ES6的用戶(hù)反而不理解在ES5下可以這么做:

//ES5
var PostInfo = React.createClass({
    handleOptionsButtonClick: function(e) {
        // Here, 'this' refers to the component instance.
        this.setState({showOptionsModal: true});
    },
    render: function(){
        return (
            <TouchableHighlight onPress={this.handleOptionsButtonClick}>
                <Text>{this.props.label}</Text>
            </TouchableHighlight>
        )
    },
});

在ES5下,React.createClass會(huì)把所有的方法都bind一遍,這樣可以提交到任意的地方作為回調(diào)函數(shù),而this不會(huì)變化。但官方現(xiàn)在逐步認(rèn)為這反而是不標(biāo)準(zhǔn)、不易理解的。

在ES6下,你需要通過(guò)bind來(lái)綁定this引用,或者使用箭頭函數(shù)(它會(huì)綁定當(dāng)前scope的this引用)來(lái)調(diào)用

//ES6
class PostInfo extends React.Component
{
    handleOptionsButtonClick(e){
        this.setState({showOptionsModal: true});
    }
    render(){
        return (
            <TouchableHighlight 
                onPress={this.handleOptionsButtonClick.bind(this)}
                onPress={e=>this.handleOptionsButtonClick(e)}
                >
                <Text>{this.props.label}</Text>
            </TouchableHighlight>
        )
    },
}

箭頭函數(shù)實(shí)際上是在這里定義了一個(gè)臨時(shí)的函數(shù),箭頭函數(shù)的箭頭=>之前是一個(gè)空括號(hào)、單個(gè)的參數(shù)名、或用括號(hào)括起的多個(gè)參數(shù)名,而箭頭之后可以是一個(gè)表達(dá)式(作為函數(shù)的返回值),或者是用花括號(hào)括起的函數(shù)體(需要自行通過(guò)return來(lái)返回值,否則返回的是undefined)。

// 箭頭函數(shù)的例子
()=>1
v=>v+1
(a,b)=>a+b
()=>{
    alert("foo");
}
e=>{
    if (e == 0){
        return 0;
    }
    return 1000/e;
}

需要注意的是,不論是bind還是箭頭函數(shù),每次被執(zhí)行都返回的是一個(gè)新的函數(shù)引用,因此如果你還需要函數(shù)的引用去做一些別的事情(譬如卸載監(jiān)聽(tīng)器),那么你必須自己保存這個(gè)引用

// 錯(cuò)誤的做法
class PauseMenu extends React.Component{
    componentWillMount(){
        AppStateIOS.addEventListener('change', this.onAppPaused.bind(this));
    }
    componentDidUnmount(){
        AppStateIOS.removeEventListener('change', this.onAppPaused.bind(this));
    }
    onAppPaused(event){
    }
}
// 正確的做法
class PauseMenu extends React.Component{
    constructor(props){
        super(props);
        this._onAppPaused = this.onAppPaused.bind(this);
    }
    componentWillMount(){
        AppStateIOS.addEventListener('change', this._onAppPaused);
    }
    componentDidUnmount(){
        AppStateIOS.removeEventListener('change', this._onAppPaused);
    }
    onAppPaused(event){
    }
}

這個(gè)帖子中我們還學(xué)習(xí)到一種新的做法:

// 正確的做法
class PauseMenu extends React.Component{
    componentWillMount(){
        AppStateIOS.addEventListener('change', this.onAppPaused);
    }
    componentDidUnmount(){
        AppStateIOS.removeEventListener('change', this.onAppPaused);
    }
    onAppPaused = (event) => {
        //把方法直接作為一個(gè)arrow function的屬性來(lái)定義,初始化的時(shí)候就綁定好了this指針
    }
}

Mixins

在ES5下,我們經(jīng)常使用mixin來(lái)為我們的類(lèi)添加一些新的方法,譬如PureRenderMixin

var PureRenderMixin = require('react-addons-pure-render-mixin');
React.createClass({
  mixins: [PureRenderMixin],

  render: function() {
    return <div className={this.props.className}>foo</div>;
  }
});

然而現(xiàn)在官方已經(jīng)不再打算在ES6里繼續(xù)推行Mixin,他們說(shuō):Mixins Are Dead. Long Live Composition。
盡管如果要繼續(xù)使用mixin,還是有一些第三方的方案可以用,譬如這個(gè)方案
不過(guò)官方推薦,對(duì)于庫(kù)編寫(xiě)者而言,應(yīng)當(dāng)盡快放棄Mixin的編寫(xiě)方式,上文中提到Sebastian Markb?ge的一段代碼推薦了一種新的編碼方式:

//Enhance.js
import { Component } from "React";

export var Enhance = ComposedComponent => class extends Component {
    constructor() {
        this.state = { data: null };
    }
    componentDidMount() {
        this.setState({ data: 'Hello' });
    }
    render() {
        return <ComposedComponent {...this.props} data={this.state.data} />;
    }
};
//HigherOrderComponent.js
import { Enhance } from "./Enhance";

class MyComponent {
    render() {
        if (!this.data) return <div>Waiting...</div>;
        return <div>{this.data}</div>;
    }
}

export default Enhance(MyComponent); // Enhanced component

用一個(gè)“增強(qiáng)函數(shù)”,來(lái)某個(gè)類(lèi)增加一些方法,并且返回一個(gè)新類(lèi),這無(wú)疑能實(shí)現(xiàn)mixin所實(shí)現(xiàn)的大部分需求。

ES6+帶來(lái)的其它好處

解構(gòu)&屬性延展

結(jié)合使用ES6+的解構(gòu)和屬性延展,我們給孩子傳遞一批屬性更為方便了。這個(gè)例子把className以外的所有屬性傳遞給div標(biāo)簽:

class AutoloadingPostsGrid extends React.Component {
    render() {
        var {
            className,
            ...others,  // contains all properties of this.props except for className
        } = this.props;
        return (
            <div className={className}>
                <PostsGrid {...others} />
                <button onClick={this.handleLoadMoreClick}>Load more</button>
            </div>
        );
    }
}

下面這種寫(xiě)法,則是傳遞所有屬性的同時(shí),用覆蓋新的className值:

<div {...this.props} className="override">
    …
</div>

這個(gè)例子則相反,如果屬性中沒(méi)有包含className,則提供默認(rèn)的值,而如果屬性中已經(jīng)包含了,則使用屬性中的值

<div className="base" {...this.props}>
    …
</div>

參考react-native中文官網(wǎng):http://reactnative.cn/post/15

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容