我有以下方法,效果很好,但我希望找到
...
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/