我得到以下错误
无法读取undefined的属性“setState”
即使在构造函数中绑定了delta。
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta.bind(this);
}
delta() {
this.setState({
count : this.state.count++
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button>
</div>
);
}
}
ES5和ES6类之间有上下文差异。所以,实现之间也会有一点不同。
以下是ES5版本:
var Counter = React.createClass({
getInitialState: function() { return { count : 1 }; },
delta: function() {
this.setState({
count : this.state.count++
});
},
render: function() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button>
</div>
);
}
});
这是ES6版本:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count : 1 };
}
delta() {
this.setState({
count : this.state.count++
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta.bind(this)}>+</button>
</div>
);
}
}
注意,除了类实现中的语法差异之外,事件处理程序绑定也存在差异。
在ES5版本中,它是
<button onClick={this.delta}>+</button>
在ES6版本中,它是:
<button onClick={this.delta.bind(this)}>+</button>