前言
不論是React還是React-native,facebook官方都推薦使用ES6的語法,沒在項目中使用過的話,突然轉換過來會遇到一些問題,如果還沒有時間系統的學習下ES6那么注意一些常見的寫法暫時也就夠用的,這會給我們的開發帶來很大的便捷,你會體驗到ES6語法的無比簡潔。下面就介紹我在react和react-native中從ES5轉到ES6中體會到的幾個對比。
ES6寫組件的區別
直接在React v0.13.0 Beta 1中一個官方的演示來說明:
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方法來創建組件對比一下:
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>
);
}
})
主要有三個區別:
創建組件的方法
用class聲明來取代了React.createClass,這里簡潔了許多。
props
- ES6中需要用在constructor中有super(props)來傳遞props。
- ES6中getDefaultProps是class的屬性而不是方法,不能定義在組件內部,需要單獨寫在外面。
- 同理,ES6中propTypes也需要寫在外面。
state
ES6不在需要getInitialState方法,而是直接在constructor中直接用this.state即可,更加方便。
this的綁定
這段代碼采用了ES6后其中onClick={this.tick.bind(this)這里需要采用bind方法來綁定this,如果不綁定this,this.tick方法的this就會指向全局,綁定了this之后將this綁定到組件實例之上。但是我們應該還記得js中bind方法每運行一次就返回一個新的函數,在react中也就是每次render都會創建一個新的函數,所以我們最好將其綁定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 };
這樣只會創建一次。當然這樣寫略顯繁瑣,有沒有更好的方法呢? 當然! ES6為我們提供了箭頭函數,根本不需要在綁定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 };
箭頭函數不會創建自身的this上下文,this就指向組件實例。建議就用箭頭函數,代碼會精簡很多。
總結
知道這幾點區別以后,再去找個教程熟悉下ES6的語法,基本就可以用ES6來寫react了,感覺js的標准越來越向java和python等靠近,前端后端都要融合了哈哈。