【发布时间】:2021-09-08 15:06:06
【问题描述】:
点击按钮时我需要调用一个函数。 我的代码是:
createButtonsArray(arr){
return arr.arr.map((key,index) =>
<input type='button' onClick={this.sayHello}/>
)}
sayHello() {
alert('Hello!');
}
现在,我收到一个错误:
Unhandled Rejection (TypeError): Cannot read property 'sayHello' of undefined
会是什么?
【问题讨论】:
-
这是一个绑定问题,您需要将
sayHello和createButtonsArray设为具有箭头函数值的属性。或者您可以在构造函数中调用this.sayHello = this.sayHello.bind(this)(createButtonsArray相同)。 -
这是在功能组件中吗?
this在功能组件中未定义。否则,您需要将this绑定到基于类的组件中的sayHello函数,或者在构造函数中,或者通过将其转换为箭头函数。