如何通过传递给函数的prop设置状态?
<button onClick={ () => this.handleClick(person2) }>
handleClick = (person) => {
console.log(person);
const value = this.state.person
console.log(value) // this returns undefined.
this.setState({ person: !value })
}
所以我想更改person2的状态。州:
this.state = {
person1: false,
person2: false,
person3: false
}
person
是在handleClick
中传递的参数。基于参数,我想更改状态。我该怎么办?
答案 0 :(得分:2)
handleClick = personNumber => {
this.setState(prevState => ({
[personNumber]: !prevState[personNumber]
}))
}