gpt4 book ai didi

javascript - 在 React 中检索多个子组件的状态

转载 作者:行者123 更新时间:2023-11-30 15:03:58 28 4
gpt4 key购买 nike

我正在制作一个小游戏作为 React 的练习。有几个选项,您可以选择您认为正确的选项,游戏会检查它们并让您知道是否正确。如何从选项按钮中检索状态?思考这个问题的“ react 方式”是什么?这是父级:

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>
)
}
}

选项按钮:

class OptionButton extends Component {
constructor(props) {
super(props)
this.state = {
selected: false
}
}
unselectSet() {
this.setState({
selected: false
})
}
selectSet() {
this.setState({
selected: true
})
}
toggler() {
this.state.selected ? this.unselectSet() : this.selectSet()
}
render() {
return (
<div>
<button onClick={() => this.toggler()} style={numberButtonStyle}>{this.props.opt}</button>
</div>
)
}
}

最佳答案

最好将状态存储在您需要它的地方,而不是在单独的组件中然后检索它。所以我会做

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

关于javascript - 在 React 中检索多个子组件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46084180/

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