question = {
quest : "How old am I?",
answers : [17,18,20,25],
correct : 17,
}
checkAnswer(){
var usersAnswer = document.getElementById('ans-1').textContent;
var answer = this.question.correct;
if(usersAnswer==answer){
alert('correct')
}else{
alert('u lost')
}
}
使用此代码,我无法从 ReactJS 中的事件处理程序访问对象。 我收到此错误:
TypeError: Cannot read property
question
ofundefined
P.S i'm begginer
最佳答案
该错误是由于 this
绑定(bind)错误造成的。您可以使用Arrow Function
checkAnswer = () => {
var usersAnswer = document.getElementById('ans-1').textContent;
var answer = this.question.correct;
if(usersAnswer==answer){
alert('correct')
}else{
alert('u lost')
}
}
您还可以使用Function.prototype.bind()
而不是箭头函数。您只需要添加 this.checkAnswer.bind(this)
。相反,如果 this.checkAnswer.bind
您要在其中设置处理程序
关于javascript - 无法从 ReactJS 中的事件处理程序访问对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55079397/