class Button extends React.Component{
constructor(props) {
super(props);
}
increament() {
this.setState({
count: this.state.count + 1
})
}
render() {
return (<button onClick={ this.increament }>增加按钮</button>);
}
}
这里会报错 Uncaught TypeError: Cannot read property 'setState' of undefined
JavaScript函数中的this不是在函数声明的时候,而是在函数运行的时候定义的
在JSX语法中: onClick={ function } onClick这个属性本身只是一个"中间变量"。将函数赋值给onClick这个中间变量,后面不仅要进行JSX语法转化,将JSX组件转换成Javascript对象,还要再将Javascript对象转换成真实DOM。把onClick作为中间变量,指向一个函数的时候,后面的一系列处理中,使用onClick这个中间变量所指向的函数,里面的this自然就丢失掉了,不是再指向对象实例了。
解决方法:
(1)在构造函数中增加
this.increament = this.increament.bind(this);
(2)或者是在render函数的事件中绑定
<button onClick={ this.increament.bind(this) }>增加按钮</button>
(3)利用箭头函数定义方法
increament = () => {
this.setState({
count: this.state.count + 1
})
}
(4)在引用时使用箭头函数
<button onClick={ () => this.increament() }>增加按钮</button>