Basheer Kohli
Basheer Kohli

Reputation: 164

Touchable Opacity function Invoking Immediately at launch of application

am newbie to js and react native.I am having a doubt in the below code . Function given as a value for the onpress property of touchable opacity is calling at the launch of application without being touching the touchable opacity. can anyone explain whats happening behind the screens.Please see the inline comment for the hello method for details.

export default class FirstClass extends Component {  

  hello(){  // this function is called at launch of application 
            // itslef .I know if i can use fat arrow function or 
            // bind function to invoke this wont call at the start 
            // of application.Can anyone explain why its calling
            // automatically in this case and what is the this 
            // refers to in this method in this case.
    console.log('Hai from method hello');
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={this.hello()}>
          <Text>FirstScreen</Text>    
        </TouchableOpacity>
      </View>
    );
   }
  }

Upvotes: 2

Views: 1620

Answers (3)

Lukasz
Lukasz

Reputation: 1842

The reason why the method is called without touching the button is, because you have () at the end, which is basically a function call. The passing this.hello you are passing a function, passing this.hello() you are calling a function and passing whatever this function returns.

Change this.hello() into this.hello.bind(this).

Upvotes: 0

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19069

Let's provide this with an explanation:

First: <TouchableOpacity onPress={this.hello}>

= no function invocation with () (that was your actual cause of an error)

= no need for .bind(this)

= no need for lambda () => this.hello() in component creation

Both of those are considered harmful anti-patterns mostly because of performance issues.

Second:

hello = () => { ... }

= this scope will remain correct, thus no need for bind

Upvotes: 2

Andrei Olar
Andrei Olar

Reputation: 2358

This happens because you immediately call the function at render time by doing it the way you do.

<TouchableOpacity onPress={this.hello()}> // This means you are directly invoking the function when the component renders. It is called as soon as the render happens.

vs

<TouchableOpacity onPress={() => this.hello()}> // You are referencing a function to React to call later when the actual event happens.

Another way said: onPress expects a function, right? You did not pass a function because in your case this.hello() does not return a function. You simply call that function and that's it. And this happens at render time.

The second way: () => this.hello() actually passes a function. And by pressing the button you are invoking the function you passed to it.

Upvotes: 5

Related Questions