Reputation: 222
I'm a lil bit confuse about calling callback in the element's prop.
Assume I have a button here.
<Button
onPress={() => { loadMore()}}
title="Load More"
backgroundColor='#0A55C4' />
What is the difference between:
onPress={() => { this.loadMore()}}
onPress={this.loadMore()}
onPress={this.loadMore}
Those all seem to be work well. But I wonder are there differences between them ?. Thanks
Upvotes: 0
Views: 671
Reputation: 85002
onPress={this.loadMore()}
This one is very likely a mistake. This means "immediately call loadMore, and pass its result in as a prop to the component". Unless loadMore is a factory which produces other functions, you probably don't want to do this.
onPress={this.loadMore}
This means "pass load more into the component". This is often what you want, but when loadMore is called, this
will be undefined unless you've taken steps to fix that. For example, you can bind the function in your constructor, or create it as an arrow function.
onPress={() => { this.loadMore()}}
This means "create a new function, and pass it into the component". This is one of the possible solutions to the issues i mentioned for the previous case.
It does have the downside that you'll be creating a new function every time render is called. Creating functions is fairly lightweight on its own, but it does mean that the Button component might compare its old onPress prop with its new onPress prop, see that they changed, and thus think it needs to rerender. This extra rerender can be a performance consideration.
Upvotes: 2
Reputation: 2840
These two are the same. In react, no need to supply the parens to a function without parameters. Also, this requires an event binding in your constructor.
onPress={this.loadMore()}
onPress={this.loadMore}
constructor() {
this.loadMore = this.loadMore.bind(this);
}
However, this syntax doesn't require the explicit bind in the constructor. You're using an arrow function.
onPress={() => { this.loadMore()}}
https://reactjs.org/docs/handling-events.html
Upvotes: 1