前言
不論是React還是React-native,facebook官方都推薦使用ES6的語(yǔ)法煌张,沒在項(xiàng)目中使用過的話,突然轉(zhuǎn)換過來會(huì)遇到一些問題庵楷,如果還沒有時(shí)間系統(tǒng)的學(xué)習(xí)下ES6那么注意一些常見的寫法暫時(shí)也就夠用的,這會(huì)給我們的開發(fā)帶來很大的便捷蹂随,你會(huì)體驗(yàn)到ES6語(yǔ)法的無比簡(jiǎn)潔锹漱。下面就介紹我在react和react-native中從ES5轉(zhuǎn)到ES6中體會(huì)到的幾個(gè)對(duì)比佩谷。
ES6寫組件的區(qū)別
直接在React v0.13.0 Beta 1中一個(gè)官方的演示來說明:
export class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
tick() {
this.setState({count: this.state.count + 1});
}
render() {
return (
<div onClick={this.tick.bind(this)}>
Clicks: {this.state.count}
</div>
);
}
}
Counter.propTypes = { initialCount: React.PropTypes.number };
Counter.defaultProps = { initialCount: 0 };
和React.createClass方法來創(chuàng)建組件對(duì)比一下:
const Counter = React.createClass ({
getDefaultProps : function () {
return {
initialCount : 0
};
},
propTypes: {
initialCount: React.PropTypes.number
},
getInitialState: function() {
return { count: this.props.initialConunt};
},
tick: function() {
this.setState({count: this.state.count + 1});
},
render: function() {
return (
<div onClick={this.tick}>
Clicks: {this.state.count}
</div>
);
}
})
主要有三個(gè)區(qū)別:
創(chuàng)建組件的方法
用class聲明來取代了React.createClass腋逆,這里簡(jiǎn)潔了許多婿牍。
props
- ES6中需要用在constructor中有super(props)來傳遞props。
- ES6中g(shù)etDefaultProps是class的屬性而不是方法惩歉,不能定義在組件內(nèi)部等脂,需要單獨(dú)寫在外面。
- 同理撑蚌,ES6中propTypes也需要寫在外面上遥。
state
ES6不在需要getInitialState方法,而是直接在constructor中直接用this.state即可争涌,更加方便露该。
this的綁定
這段代碼采用了ES6后其中onClick={this.tick.bind(this)這里需要采用bind方法來綁定this,如果不綁定this第煮,this.tick方法的this就會(huì)指向全局解幼,綁定了this之后將this綁定到組件實(shí)例之上。但是我們應(yīng)該還記得js中bind方法每運(yùn)行一次就返回一個(gè)新的函數(shù)包警,在react中也就是每次render都會(huì)創(chuàng)建一個(gè)新的函數(shù)撵摆,所以我們最好將其綁定constructor中:
export class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
this.tick = this.tick.bind(this);
}
tick() {
this.setState({count: this.state.count + 1});
}
render() {
return (
<div onClick={this.tick}>
Clicks: {this.state.count}
</div>
);
}
}
Counter.propTypes = { initialCount: React.PropTypes.number };
Counter.defaultProps = { initialCount: 0 };
這樣只會(huì)創(chuàng)建一次。當(dāng)然這樣寫略顯繁瑣害晦,有沒有更好的方法呢特铝? 當(dāng)然! ES6為我們提供了箭頭函數(shù)壹瘟,根本不需要在綁定this這種操作了鲫剿。
export class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
tick = () => {
this.setState({count: this.state.count + 1});
}
render() {
return (
<div onClick={this.tick}>
Clicks: {this.state.count}
</div>
);
}
}
Counter.propTypes = { initialCount: React.PropTypes.number };
Counter.defaultProps = { initialCount: 0 };
箭頭函數(shù)不會(huì)創(chuàng)建自身的this上下文,this就指向組件實(shí)例稻轨。建議就用箭頭函數(shù)灵莲,代碼會(huì)精簡(jiǎn)很多。
總結(jié)
知道這幾點(diǎn)區(qū)別以后殴俱,再去找個(gè)教程熟悉下ES6的語(yǔ)法政冻,基本就可以用ES6來寫react了,感覺js的標(biāo)準(zhǔn)越來越向java和python等靠近线欲,前端后端都要融合了哈哈明场。