節選自:這個網址
模塊引用
在ES5里,如果使用CommonJS標準,引入React包基本通過require進行,代碼類似這樣:
//ES5
var React = require("react");
var { Component, PropTypes} = React; //引用React抽象組件var
在ES6里,import寫法更為標準
//ES6
import React, { Component, PropTypes,} from 'react';
導出單個類
在ES5里,要導出一個類給別的模塊用,一般通過module.exports來導出
//ES5
var MyComponent = React.createClass({ ...});
module.exports = MyComponent;
在ES6里,通常用export default來實現相同的功能:
//ES6
export default class MyComponent extends Component{ ...}
引用的時候也類似:
//ES5
var MyComponent = require('./MyComponent');
//ES6
import MyComponent from './MyComponent';
注意導入和導出的寫法必須配套,不能混用!
定義組件
在ES5里,通常通過React.createClass來定義一個組件類,像這樣:
//ES5
var Photo = React.createClass({
render: function() {
return ( <Image source={this.props.source} /> );
}
});
在ES6里,我們通過定義一個繼承自React.Component的class來定義一個組件類,像這樣:
//ES6
class Photo extends React.Component {
render() {
return ( <Image source={this.props.source} /> );
}
}
給組件定義方法
從上面的例子里可以看到,給組件定義方法不再用 名字: function()
的寫法,而是直接用名字(),在方法的最后也不能有逗號了,可以有分號
//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} /> );
}
}
定義組件的屬性類型和默認屬性
在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 /> ); } // 注意這里既沒有分號也沒有逗號
}
注意: 對React開發者而言,static成員在IE10及之前版本不能被繼承,而在IE11和其它瀏覽器上可以,這有時候會帶來一些問題。React Native開發者可以不用擔心這個問題。
初始化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, };
}
}
把方法作為回調提供
很多習慣于ES6的用戶反而不理解在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會把所有的方法都bind一遍,這樣可以提交到任意的地方作為回調函數,而this不會變化。但官方現在逐步認為這反而是不標準、不易理解的。
在ES6下,你需要通過bind來綁定this引用,或者使用箭頭函數(它會綁定當前scope的this引用)來調用
//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> )
},
}
箭頭函數實際上是在這里定義了一個臨時的函數,箭頭函數的箭頭=>
之前是一個空括號、單個的參數名、或用括號括起的多個參數名,而箭頭之后可以是一個表達式(作為函數的返回值),或者是用花括號括起的函數體(需要自行通過return來返回值,否則返回的是undefined)。
// 箭頭函數的例子
()=>1
v=>v+1
(a,b)=>a+b
()=>{
alert("foo");
}
e=>{ if (e == 0){
return 0;
}
return 1000/e;
}
需要注意的是,不論是bind還是箭頭函數,每次被執行都返回的是一個新的函數引用,因此如果你還需要函數的引用去做一些別的事情(譬如卸載監聽器),那么你必須自己保存這個引用
// 錯誤的做法
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){ }
}
從這個帖子中我們還學習到一種新的做法:
// 正確的做法
class PauseMenu extends React.Component{
componentWillMount(){
AppStateIOS.addEventListener('change', this.onAppPaused);
}
componentDidUnmount(){ AppStateIOS.removeEventListener('change', this.onAppPaused);
}
onAppPaused = (event) => {
//把方法直接作為一個arrow function的屬性來定義,初始化的時候就綁定好了this指針
}
}