我正在学习reactjs并构建了一个类似于tic toe app from on reactjs official website的示例应用程序。
当我在下面运行应用程序并单击其中一个选项按钮时,它会显示Uncaught TypeError: Cannot read property 'setAnswered' of undefined
。我无法看到我在onClick实例方法上的方式与使用tic toe app的方式之间的区别。我错过了什么?
import React from 'react';
import ReactDOM from 'react-dom';
function Choice(props) {
return (
<li>
<button onClick={props.onClick}>
{props.value}
</button>
</li>
);
}
class ChoiceList extends React.Component {
constructor(props) {
super(props);
this.state = {
choices: null,
answered: false,
};
}
setAnswered() {
this.setState({
choices: this.state.choices,
answered: true});
}
renderChoice(choice) {
return <Choice key={choice} value={choice} onClick={() => this.setAnswered()}/>;
}
showData(payload) {
const answered = false;
const choices = payload.choices;
this.setState({choices: choices, answered: answered});
}
componentDidMount() {
this.showData({choices: ['Good', 'Bad']});
}
render() {
if (!this.state.choices) {
return null;
}
return (
<div id="choices">
<ul id="unsortedList">
{this.state.choices.map(this.renderChoice)}
</ul>
</div>
);
}
}
ReactDOM.render(
<Question />,
document.getElementById('root')
);
答案 0 :(得分:1)
答案 1 :(得分:0)
这是因为&#34;这个&#34;绑定到Choice元素中的onClick函数,而不是组件类。以下应该有效:
renderChoice(choice) {
return <Choice key={choice} value={choice} onClick={this.setAnswered.bind(this)}/>;
}
答案 2 :(得分:0)
这就是你的构造函数应该如何,你必须绑定&#39;这个&#39;上下文 setAnswered 。
constructor(props) {
super(props);
this.setAnswered = this.setAnswered.bind(this);
this.state = {
choices: null,
answered: false,
};
}