简体   繁体   中英

How to toggle state in React Native

I am developing a light weight project using React Native, and I encountered some setbacks, I couldn't figure it out. :(

I have a page that contains a Yes and a No button and a Yes/No render area, users will be able to click on either of the buttons. According to the users' choice, an avatar will appear in the correct render area (click yes, the avatar will be in the Yes area...). But one user can only be able to click once. I am trying to solve this using state and setState , but couldn't get it to work.

I have: this.state = {invitedState : false} and a function (part)

    onPress={() => {
      if (this.state.invitedState) {
        onPress();
      }
      this.setState(prevState => ({
        invitedState: !prevState.invitedState,
      }));
    }}

Should I not use setState to solve this problem? thanks!

I think I understand your problem. Something like this?

  state = {
    toggleUI: true,
    userToggled: false
  };

  handleToggleUI = e => {
    this.setState(currentState => {
      if ( this.state.userToggled === false ) {
        return {
          toggleUI: !currentState.toggleUI,
          userToggled: true
        };  
      }
    });
  };

You could try:

onPress{() => {
    let tempVar = this.state.invitedState ? false : true;
    this.setState({invitedState: tempVar});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM