反应-通过传递的参数更改状态

时间:2019-09-02 10:07:48

标签: javascript reactjs react-native

如何通过传递给函数的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中传递的参数。基于参数,我想更改状态。我该怎么办?

1 个答案:

答案 0 :(得分:2)

handleClick = personNumber => {
   this.setState(prevState => ({
      [personNumber]: !prevState[personNumber]
   }))
}