我在React中整理了一个小游戏作为练习。有几个选项,你选择你认为正确的那个,游戏会检查它们并让你知道你是否得到它。如何从选项按钮检索状态?什么是"反应方式"想到这个?这是父母:
[1, 2, 3, 4, 5, 6, 7, 9]
答案按钮:
class Game extends Component {
constructor(props) {
super(props)
this.answerHandler = this.answerHandler.bind(this)
}
answerHandler(event) {
event.preventDefault()
// Get answer array, check answer??
}
render() {
const optArr = ["A", "B", "C", "D", "E"]
return(
<div>
{optArr.map((opt, i) => <OptionButton opt={opt} key={i} />)}
<AnswerButton answerHandler={this.answerHandler} />
</div>
);
}
}
选项按钮:
class AnswerButton extends Component {
render() {
return(
<div>
<button type="button" onClick={this.props.answerHandler}>Submit Answer!</button>
</div>
)
}
}
答案 0 :(得分:2)
最好将状态存储在您需要它的地方,而不是单个组件然后检索它。所以我会做
class Game extends Component {
constructor(props) {
super(props)
this.answerHandler = this.answerHandler.bind(this)
}
answerHandler(event) {
event.preventDefault()
// Get answer array, check answer??
}
handleOptionChange( event ) {
//store the option state here, ready for when we need it
}
render() {
const optArr = ["A", "B", "C", "D", "E"]
return(
<div>
{
optArr.map(
(opt, i) => <OptionButton
opt={opt}
key={i}
onOptionChange={ this.handleOptionChange }
/>)
}
<AnswerButton answerHandler={this.answerHandler} />
</div>
);
}
}