純粹翻譯與整理這篇: refactoring react component to es6 classes
自react 0.13開始,官方都鼓勵使用 ES6 classes 來撰寫react元件了, 當然趁現在的空檔,從善如流的將react 0.12的程式碼翻寫一下。
如果有寫過OO的應該都會很有熟悉感。
var ExampleComponent = React.createClass({ ... });
ExampleComponent.propTypes = {
aStringProp: React.PropTypes.string
};
ExampleComponent.defaultProps = {
aStringProp: ''
};
就不再需要createClass
method啦, class直接繼承React.Component
:
class HelloComponent extends React.Component {
render() {
return <h1 onClick={this._handleClick}>Hello</h1>;
}
_handleClick() {
console.log(this);
}
}
method前面也不在需要function
keyword。
React的createClass
method好用的地方在於, 他會將我們的methods自動榜定(binding)到component einstance去, 但是我們寫ES6 classes, 就要自己處理binding, react團隊建議作prebinding:
class HelloComponent extends React.Component {
constructor() {
super();
this. _handleClick = this. _handleClick.bind(this);
}
render() {
return <h1 onClick={this._handleClick}>Hello</h1>;
}
_handleClick() {
console.log(this); // this 就是一個HelloCompoenent
}
}
把getgetInitialState
method移除, 將初始化state的動作放到constructor裡:
class HelloComponent extends React.Component {
constructor() {
super();
this. _handleClick = this. _handleClick.bind(this);
this.state = Store.getState();
}
// ...
}
撰寫base component來處理method prebinding:
class BaseComponent extends React.Component {
_bind(...methods) {
methods.forEach( (method) => this[method] = this[method].bind(this) );
}
}
以後寫的元件, 只要繼承這個base component, 就可以很方便的:
class ExampleComponent extends BaseComponent {
constructor() {
super();
this._bind('_handleClick', '_handleFoo');
}
// ...
}
Refactoring React Components to ES6 Classes