lernerbot
lernerbot

Reputation: 903

TouchableHighlight onPress not working

I implemented a sign in page that worked up until I upgraded react-native.

The problem I'm having is that the onPress prop isn't being called:

<TouchableHighlight style={styles.button}
        underlayColor='#f1c40f'
        onPress={this.signIn}>
   <Text style={styles.buttonText}>Sign In</Text>
</TouchableHighlight>

Here is my signIn function:

signIn: function(){
console.log("SignInAction signIn")
this.fetchData();  },

The signIn button appears to be depressed when I click it but the log statement isn't firing.

Upvotes: 17

Views: 21708

Answers (3)

call_de_amberlamps
call_de_amberlamps

Reputation: 419

Also, if you don't wanna use bind and since we're using ES6 syntax, you could write your function out assigned as a const and arrow-function (within your component) rather than a function eg:

signIn = () => {
  // code here
}

then you can still call it within the component like you already are without having to bind within the constructor or anywhere else:

<TouchableHighlight style={styles.button}
        underlayColor='#f1c40f'
        onPress={this.signIn}>
   <Text style={styles.buttonText}>Sign In</Text>
</TouchableHighlight>

This should keep context of "this" consistent since signIn will be bound to the component only once on initialization.

Upvotes: 3

李振纲
李振纲

Reputation: 382

you can also do it like this:

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

the rest of code don't need change.

Upvotes: 5

Nader Dabit
Nader Dabit

Reputation: 53711

Try calling it like this:

onPress={ () => this.signIn() }>

It looks like the "this" in your function is bound to the wrong scope.

Upvotes: 35

Related Questions