Wasteland
Wasteland

Reputation: 5399

react-native - calling functions as arguments

I've got a sneaking suspicion this question might be more todo with JavaScript and/or specifically ES6 than React-Native but I'll try. I have got the following component:

export default class Body extends Component {

  componentWillMount() {
    this.refresh();
  }

  clickme() {
    console.log('I have been pressed!!!!!');
  }

  refresh() {
    this.props.populateGrid();
  }
  render() {
    return (
      <View style={styles.body}>
        <Grid inGrid={this.props.grid} />
        <Button
          onPress={this.clickme}
          title={'PressMe'}
        />
      </View>
    );
  }

}

First, I passed 'this.clickme()' to onPress. It didn't work. It was only after removing the braces it started working. Why? Don't we usually call a function including the ()? Also sometimes, you have to pass it in the following format something={() => this.clickme()}. Why/When?

So when do we call function as:

1. {this.clickme}
2. {this.clickme()}
3. {() => this.clickme()}

Thank you.

Upvotes: 0

Views: 1969

Answers (1)

jarg jeeooorrrrb
jarg jeeooorrrrb

Reputation: 36

Short answer:

1 and 3 as you define in your question are effectively the same for Button.onPress -- they are passing in references to function bodies. However, #3 is also defining a new function inline, though it is defined in a very lightweight way. #2 is attempting to call the function inline. You might want to do this (#2) in some cases where you need to pass a number or boolean or string value to a property rather than a callback function as Button.onPress requires.

Longer answer:

The syntax required is defined by the signature of the method you're passing data to on the react component. In this case, we're talking about Button.onPress, which has the signature () => {} -- which means it takes in a callback function and won't pass any arguments to it when called. You don't want to call the function immediately, since the user is not clicking when you define the component. They are clicking some random time later.

Since you need to pass in a function and not its result, you don't want to include the () at the end of the function name. The parentheses will cause the function to be run immediately, whereas the name alone will simply pass a reference to the function body. That reference will be later called by Button.onPress to handle the user interaction.

A lot of JavaScript (and React) is written with a pattern of passing around function references and later calling those functions from within other functions. If you're not familiar with that pattern, definitely spend some time reading about callback patterns.

() => {} is also a shorthand way to define an inline anonymous function. It's called an arrow function, and it can have some performance gains over defining separate function bodies.

More info here:

Upvotes: 2

Related Questions