Search code examples
javascriptbuttonreact-nativeonpress

React-Native Button On Press doesn't work


I can't bind my onPress method to my JSX button. I've tried already tons of different solutions but none of them worked.

onPress Method:

class ScreenEnterPlayerNames extends Component {

  constructor(props) {
    super(props);
  }

  static navigationOptions = {
    title: 'Player Names',
  };

  onPressStartTheGame = () => {
    console.log("Pushed button Start the Game!")
    //dispatch({ type: ADD_PLAYER_NAME, playerNumber: 5, playerName: "Sandro" })
  }

Button:

return (
      <View style={styles.viewMain}>
        <View style={styles.viewTxt}>
          <Text style={styles.TxtHeading}>
            Please enter the names in sequence.
          </Text>
        </View>
        <ScrollView style={styles.viewTextBox}>
          {textBoxes}
        </ScrollView>

        <View style={styles.viewButton}>
          <Button
            title='Start the Game!'
            onPress={() => this.onPressStartTheGame}
          />
        </View>
      </View>
    );
  }
}

I've tried it with following approaches as well:

onPress={this.onPressStartTheGame}
onPress={this.onPressStartTheGame()}
onPress={this.onPressStartTheGame.bind(this)}
onPress={() => this.onPressStartTheGame.bind(this)}

And I tried to change the function to:

onPressStartTheGame()  {...

So I am pretty sure there is something else wrong but I can't figure out what.

Thank you! :-)


Solution

  • Try this for your method

     onPressStartTheGame(){
        console.log("Pushed button Start the Game!")
        //dispatch({ type: ADD_PLAYER_NAME, playerNumber: 5, playerName: "Sandro" })
      }
    

    and call it like

    onPress={this.onPressStartTheGame.bind(this)}
    

    here you can double check and try the behave in a sandbox. https://facebook.github.io/react-native/docs/handling-touches.html