javascript - 根据来自 e.target 的值 react 更新状态

标签 javascript reactjs ecmascript-6

我有以下方法,效果很好,但我希望找到

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

有没有可能做这样的事情?

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

显然这行不通,但我不想重复不必要的 if 语句。 “data-option”属性返回一个整数,所以我想用它来动态更新状态属性,而不是 button1、button2、button3 ......

最佳答案

是的,几乎就像你有:

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

假设值为 1、2、3 或 4(而您当前的代码不是)。如果不是,我们需要一个守卫:

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

关于javascript - 根据来自 e.target 的值 react 更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49388529/

相关文章:

php - javascript 相互减去日期数字

Javascript:如何安全地使用 eval()

javascript - 在 react 中更新新的 document.body.offsetHeight

javascript - 从 Material UI 中的 TableRow 组件获取数据

javascript - 更新内容时出错

javascript - 如何使用 Azure 移动服务中的使用逻辑验证数据

javascript - 有没有办法随机化 CSS/JavaScript 中的填充?

javascript - stub es6 getter setter 与 sinon

具有日期升序的Javascript数组过滤器并删除重复项

javascript - 迭代器和可迭代器之间的区别