简体   繁体   中英

React update state based on value from e.target

I have the following method which works fine, however I was hoping to find

...
  handleClick = (e) => {
    this.props.onClick()

    if(this.props.getAnswer(e)) {
      console.log('correct')
      //this.setState({ [this.state.button+ e.target.getAttribute('data-option')]: 'correct' });
      if(e.target.getAttribute('data-option') == 1){
        this.setState({
          button1: 'correct'
        })
      }
      if(e.target.getAttribute('data-option') == 2){
        this.setState({
          button2: 'correct'
        })
      }
      if(e.target.getAttribute('data-option') == 3){
        this.setState({
          button3: 'correct'
        })
      }
      if(e.target.getAttribute('data-option') == 4){
        this.setState({
          button4: 'correct'
        })
      }
    }
  }
...

would it be possible to do something like this?

    this.setState({
      button[e.target.getAttribute('data-option')]: 'correct'
    })

obviously this doesn't work but I didn't want to repeat unnecessary if statements. The "data-option" attr returns an integer so I wanted to use that to update the state property dynamically instead of button1, button2, button3 .....

Yes, and very nearly like you have:

this.setState({
    ["button" + e.target.getAttribute('data-option')]: 'correct'
});

That assumes the value is 1, 2, 3, or 4 (whereas your current code doesn't). If it may not be, we need a guard:

var option = e.target.getAttribute('data-option');
if (option >= 1 && option <= 4) { // Coerces to number, NaN won't match
    this.setState({
        ["button" + option]: 'correct'
    });
}
this.setState({
    ["button"+e.target.getAttribute('data-option')] : 'correct'
})

You can use ES6 template literal:

this.setState({
  [`button${e.target.getAttribute('data-option')}`]: 'correct'
});

Edit: use brackets for computed property name, without brackets you would get SyntaxError: expected property name, got template literal. See TJ Crowder 's answer, it's the best one so far.

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