我在React教程页面上读到,ES6将使用构造函数来初始化状态.
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 };
Run Code Online (Sandbox Code Playgroud)
然后继续,使用ES7语法实现同样的事情.
// Future Version
export class Counter extends React.Component {
static propTypes = { initialCount: React.PropTypes.number };
static defaultProps = { initialCount: 0 };
state = { count: this.props.initialCount };
tick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div onClick={this.tick.bind(this)}>
Clicks: {this.state.count}
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么ES7比ES6版本或ES5版本更好.
谢谢
Nou*_*our 19
ES7更好,因为它支持以下方案:
注意:使用ES7定义状态时,您正在使用Property initializers功能
| 归档时间: |
|
| 查看次数: |
17123 次 |
| 最近记录: |