How to toggle boolean state of react component?

前端 未结 9 1725
别跟我提以往
别跟我提以往 2021-01-29 23:45

I\'d like to know how to toggle a boolean state of a react component. For instance:

I have boolean state check in the constructor of my component:

const         


        
9条回答
  •  鱼传尺愫
    2021-01-30 00:44

    Since nobody posted this, I am posting the correct answer. If your new state update depends on the previous state, always use the functional form of setState which accepts as argument a function that returns a new state.

    In your case:

    this.setState(prevState => ({
      check: !prevState.check
    }));
    

    See docs


    Since this answer is becoming popular, adding the approach that should be used for React Hooks (v16.8+):

    If you are using the useState hook, then use the following code (in case your new state depends on the previous state):

    const [check, setCheck] = useState(false);
    // ...
    setCheck(prevCheck => !prevCheck);
    

提交回复
热议问题