简体   繁体   中英

Retrieving states of multiple child components in React

I'm putting together a little game as an exercise in React. There are a few options, you pick the one's you think are right, the game checks them and lets you know if you got it. How do I retrieve the state from the option buttons? What is the "React way" of thinking about this? Here is the parent:

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

The answer button:

class AnswerButton extends Component {
  render() {
    return(
      <div>
        <button type="button" onClick={this.props.answerHandler}>Submit Answer!</button>
      </div>
    )
  }
}

The option button:

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

It's much better to store the state in the place where you're going to need it, rather than in the individual components and then retrieve it. So I'd do

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM