Search code examples
react-nativestyles

Changing styles onPress event React Native


I've a problem with changing styles using onPress event, originally i've width = 75 and height too (default values of width and height), but When I use onPress I want to trigger the method (method What I would like to use for replace styles value) which will replace value of width and height to 65. Can you tell me any solution for solve this problem?


Solution

  • You could use a touchableHighlight with is imported from 'react-native' Your constructor should hold a varaible for the press status:

    constructor(props) {
      super(props);
      this.state = {
        pressStatus: false 
      };
    }
    

    The two function that handles when the touchableHighlight is pressed.

    _onHideUnderlay(){
      this.setState({ pressStatus: false });
    }
    _onShowUnderlay(){
      this.setState({ pressStatus: true });
    }
    

    The touchable could look like

    <TouchableHighlight
            onPress={()=>{}}
            activeOpacity={0.5}
            style={this.state.pressStatus ? styles.buttonPress : styles.button}
            onHideUnderlay={this._onHideUnderlay.bind(this)}
            onShowUnderlay={this._onShowUnderlay.bind(this)}
            >
      <Text>Press</Text>
    </TouchableHighlight>
    

    Then add to the styleSheet

    button: {
        alignSelf:'center',
        borderColor: '#000066',
        backgroundColor: '#000066',
        width:65,
        height:65
      },
      buttonPress: {
        alignSelf:'center',
        borderColor: '#000066',
        backgroundColor: '#000066',
        width:75,
        height:75
      },