我知道讨论范围问题的类似线程。反应 - 无法读取null属性'setState'
使用下列组件
import React from 'react';
import ReactDOM from 'react-dom';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
}
addMore() {
this.setState({
counter: this.state.counter + 1
});
}
render() {
return (
<div onClick={ this.addMore }>
<p>counter: { this.state.counter }</p>
</div>
);
}
}
if (document.getElementById('example')) {
ReactDOM.render(<Example />, document.getElementById('example'));
}
当你点击div
你Cannot read property 'setState' of null
我知道你可以做这样的事情this.addMore.bind(this)
但是这一切似乎不可思议额外的样板式的代码只是为了让工作。
什么被认为是最优雅的方式来做到这一点?当然,人们必须有一个有利的方式,而不是眼睛疼痛?
类的属性提案可能是最优雅的解决方案,如下所示:http://stackoverflow.com/a/34050078/218196。 –
http://blog.andrewray.me/react-es6-autobinding-and-createclass/ –