这是我的第一个 React 应用程序,我已经阅读了官方教程/文档并遵循那里的指南。我以为我对这些概念有很好的理解,但显然我遗漏了一些东西,因为我无法将值和 id 传递回父组件,所以我可以在父组件中进行评分。
基本上这是一个简单的测验(或问答)应用程序,其中数组 [0] 是问题,数组 [1] 是答案:allProblems = [[q1,a1],[q2,a2], ... ].
class ChildComponent extends React.Component {
inputAnswer(id, e) {
e.preventDefault();
this.props.onAnswer(e.target.value, id);
}
render() {
const { problem, id, answer } = this.props;
return (
<li>
{problem[0]} = <input value={answer} onChange={(e) => this.inputAnswer(id, e)} />
</li>
);
}
}
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
answer: null,
};
}
handleAnswer(answer, id) {
alert(id);
this.setState({
answer: answer,
})
}
render() {
const rows = [];
this.props.allProblems.forEach((problem, index) => {
rows.push(
<ChildComponent
key={index}
problem={problem}
id={index}
answer={this.state.answer}
correct={this.state.correct}
onAnswer={() => this.handleAnswer()}
/>
);
});
return (
<div>
<h1>Problems</h1>
<ul>{rows}</ul>
</div>
);
}
}
谢谢!
最佳答案
你有这个:
onAnswer={() => this.handleAnswer()}
在父组件的 forEach 回调中。
你需要的是:
onAnswer={(answer, id) => this.handleAnswer(answer, id)}
否则,handleAnswer 不会收到任何东西。
所以总的来说,在你的回调中你应该插入这个:
<ChildComponent
key={index}
problem={problem}
id={index}
answer={this.state.answer}
correct={this.state.correct}
onAnswer={(answer, id) => this.handleAnswer(answer, id)}
/>
更多信息(可选):
您还可以通过使处理程序成为箭头函数来压缩代码并提高性能,这意味着您在使用“this”时不必担心它的值。因此,在您的子组件中,您可以将处理程序更改为:
handleAnswer = (answer, id) => {
alert(id);
this.setState({
answer: answer,
})
}
然后你可以这样做:
onAnswer={this.handleAnswer}
关于javascript - 从 onClick 事件处理程序向 React 中的父组件传递参数的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48376012/