在React的Class组件中写事件响应函数需要在constructor中绑定this
class Test extends React.Component {
constructor(props) {
super(props);
this.onClickButton = this.onClickButton.bind(this);
this.state = {
count: 0,
}
}
onClickButton() {
console.log(this, 'this')
console.log(this.state.count)
}
render(): React.ReactNode {
return (
<div>
<div>{this.state.count}</div>
<button onClick={this.onClickButton}>按钮</button>
</div>
)
}
}
export default Test;
原因是如果未进行绑定this,在事件函数中this指向会丢失,this打印为undefined。
这个不是React的问题,而是javascript本身的特性。
在未绑定之前,onClickButton在原型上
onClick接收this.onClickButton作为回调,当点击发生时类似于:
const test = new Test();
button.onclick = test.onClickButton;
button.click();
函数调用时等同于函数直接调用的情况,在class的写法为严格模式,故this打印为undefined。
当绑定this后:
button.onclick = test.onClickButton.bind(test);
button.click();
当定义事件函数为箭头函数时不会出现this为undefined的情况,因为箭头函数本身没有this,内部this就是定义时上层作用域的this。