gpt4 book ai didi

javascript - 无法将 react 组件方法作为 prop 回调提供给另一个功能组件

转载 作者:行者123 更新时间:2023-11-30 20:36:10 26 4
gpt4 key购买 nike

我正在学习 reactjs 并构建了一个类似于 tic toe app from on reactjs official website 的示例应用程序.

当我运行下面的应用程序并单击其中一个选择按钮时,它显示 Uncaught TypeError: Cannot read property 'setAnswered' of undefined。我看不出我将实例方法挂接到 onClick 的方式与 tic toe 应用程序执行它的方式之间的区别。我错过了什么?

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')
);

最佳答案

将以下代码附加到构造函数

constructor(props) {
super(props);
this.state = {
choices: null,
answered: false,
};

this.setAnswered = this.setAnswered.bind(this);
this.renderChoice = this.renderChoice.bind(this);
this.showData = this.showData.bind(this);
}

检查链接供您引用 Function.prototype.bind()

关于javascript - 无法将 react 组件方法作为 prop 回调提供给另一个功能组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49814898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com