Bre
Bre

Reputation: 79

React Native function not recognised on TouchableOpacity function "onPress"

I dont understand why the first example of code renders ok onPress of the button and the other example when I put it inside a fundtion it does not recognise the function.

//This executes as expected

 render() {
   return (

     <View style={styles.container}>

       <TouchableOpacity onPress={this.handlePress.bind(this)}>

          <Text style={{paddingTop: 10, paddingLeft: 10, color: 
         '#FF0000'}}>Prova</Text>

       </TouchableOpacity>

     </View>

-------------------------------------------------------------------
//Here it can't recognise the function

func1(){
 this.handlePress.bind(this);
 };


 render() {
   return (

     <View style={styles.container}>

       <TouchableOpacity onPress={this.func1()}>

          <Text style={{paddingTop: 10, paddingLeft: 10, color: 
         '#FF0000'}}>Prova</Text>

       </TouchableOpacity>

     </View>

Upvotes: 0

Views: 70

Answers (2)

Hend El-Sahli
Hend El-Sahli

Reputation: 6752

Convert your function to an arrow function, and forget about binding... Arrow function is automatically bound to its parent...

handlePress = () => {};

-

<TouchableOpacity onPress={this.handlePress}>

Upvotes: 2

nicecatch
nicecatch

Reputation: 1737

You do not need to bind this.handlePress.bind(this); inside func1.

Just call it

func1(){
    this.handlePress()
}

With this.handlePress.bind(this), you are not invoking the function, but just returning a function bounfd to 'this'

Upvotes: 0

Related Questions