轉載鏈接:http://www.ncloud.hk/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/react-native-es5-and-es6-writing-table/
對於很多初次學習React-Native人來說,都會爲ES6語法所困惑,因爲網上好多React-Native的Demo都是用ES5語法寫的。所以我剛開始也是學的ES5,對我來說ES5語法比較熟悉,但是看到ES6的語法剛開始就感覺怪怪的,相信對初次接觸ES6寫法的
人來說都會有這樣的感覺。今天我就整理下ES5跟ES6寫法的規範,希望會對你有所幫助。
一、模塊引用
在ES5裏引入React的包基本通過require進行,代碼如下:
//ES5
var React=require('react-native'); var { Image, Text, propTypes }=React;
二、導出單個類
//在ES6中用,import導入
import React,{Image,Text,PropTypes} from 'react-native'
在ES5中,一般通過module.exports來導出
//ES5
var MyComponent=React.createClass({ ..... }), module.exports=MyComponent;
//ES6
export default class MyComponent extends React.component{ .... }
引用的時候:
//ES5
var MyComponent=require('./MyComponent.js');
//ES6
import MyComponent from './MyComponent.js'
三、定義組件
在ES5中,通過React.createClass來定義一個組件類。如下所示:
//ES5
var MyComponent=React.createClass({ render:function(){ return ( <Text>...</Text> ); } })
在ES6裏,通過定義一個繼承自React.Component的class來定義一個組件:
//ES6
class MyComponent extends React.component{ render(){ return( <Text>...</Text> ) } }
四、給組件定義方法
從上面可以看出給組件定義方法不再用 函數名:function()的寫法,而是直接名字,方法的後面也不用用逗號(,)
五、定義組件的屬性類型和默認屬性
在ES5裏,屬性類型和默認屬性分別通過propTypes成員和getDefaultProps方法來實現
//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裏,可以統一使用static成員來實現
//ES6 class Video extends React.Component { static defaultProps = { autoPlay: false, maxLoops: 10, }; // 注意這裏有分號 static propTypes = { autoPlay: React.PropTypes.bool.isRequired, maxLoops: React.PropTypes.number.isRequired, posterFrameSrc: React.PropTypes.string.isRequired, videoSrc: React.PropTypes.string.isRequired, }; // 注意這裏有分號 render() { return ( <View /> ); } // 注意這裏既沒有分號也沒有逗號 }
六、初始化state
ES5如下:
//ES5 var Video = React.createClass({ getInitialState: function() { return { loopsRemaining: this.props.maxLoops, }; }, })
ES6如下:
//ES6 class Video extends React.Component { state = { loopsRemaining: this.props.maxLoops, } } 不過我們推薦更易理解的在構造函數中初始化(這樣你還可以根據需要做一些計算): //ES6 class Video extends React.Component { constructor(props){ super(props); this.state = { loopsRemaining: this.props.maxLoops, }; } }
七、把方法作爲回調提供
//ES5
var MyComponent=React.createClass({ _example:function(){ console.log('example') }, render:function(){ return( <View> <TouchableHighlight onPress={this._example}> <Text>...</Text> </TouchableHighlight> </View> ) } })
//在ES6下可以通過bind來綁定引用,或者使用箭頭函數(它會綁定當前的scope的this引用)來調用
class MyComponent extends React.component{ _example(){ console.log('example') } render(){ return( <View> <TouchableHighlight onPress={this._example.bind(this) or ()=>{this._example()}}> <Text>...</Text> </TouchableHighlight> </View> ) } }