How to render my button again in React Native?

Asked

Viewed 126 times

2

I have this button that should have a background-color depending on the state:

<TouchableOpacity onPress={this._onPressButtonMassa}>
  <View style={[styles.button, this.props.hipertrofia === 'sim' ?
  { backgroundColor: 'black' } : { backgroundColor: 'white' }]}>
     <Icon name="bicycle" size={50} color="#FAFAFA" />
     <Text style={styles.buttonText}>Quero ganhar massa</Text>
  </View>
</TouchableOpacity>

When I click on that button the state is changed:

  _onPressButtonMassa = () => {
    this.setState({ hipertrofia: 'sim' }); 
    this.setState({ perdapeso: 'nao' }); 
  };

But the button starts with the background-color white, and when the state is changed it does not render the button again, remaining white regardless of the value of this.props.hipertrofia

How can I render my button again so that it changes to the background-color black when you click on it?

1 answer

3


You’re pointing to this.props.hypertrophy, so you’re not altering it...

Establish the value of state hypertrophy for this.props.hypertrophy in the constructor, and on your button, switch this.props.hypertrophy to this.state.hypertrophy

constructor(props) {
  super(props); //importante chamar super(props)!

  this.state = {
    hipertrofia: this.props.hipertrofia
    perdapeso: this.props.perdapeso
    //outros estados
  }
}

_onPressButtonMassa = () => {
  this.setState({ hipertrofia: 'sim' }); 
  this.setState({ perdapeso: 'nao' }); 
};

<TouchableOpacity onPress={this._onPressButtonMassa}>
  <View style={[styles.button, this.state.hipertrofia === 'sim' ?
  { backgroundColor: 'black' } : { backgroundColor: 'white' }]}>
  //...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.