Reputation: 333
So When I try to pass in goBack function as a reference it doesn't work for some reason, I need to encapsulate it as an anonymous function for it to work. Is there a reason why this is the case?
I want this to work! (Below)
<Button onPress={this.props.navigation.goBack} />
But only this works (Below)
<Button onPress={() => this.props.navigation.goBack()} />
Is this
loosing its reference? Thanks!
EDIT: I noticed that the document also uses anonymous function to invoke goBack
. Curious why this is the case.
Upvotes: 1
Views: 575
Reputation: 1291
The reason why <Button onPress={this.props.navigation.goBack} />
does not work is that goBack
expect a null
or undefined
as the first parameter to have the default behavior of going back just one screen.
When you use the handler like this onPress={this.props.navigation.goBack}
, the handler will invoke goBack
with the event that is passed back by the handler, i.e. this.props.navigation.goBack(event)
.
event
is not null so the goBack
function will try to pass that as a key to the screen to goBack
from. https://reactnavigation.org/docs/navigators/navigation-prop#goBack-Close-the-active-screen-and-move-back. Then, event
does not match to any of your pre-defined key, so the routing has no effect.
Upvotes: 2
Reputation: 2090
Yes, that is your issue most likely.
try: <Button onPress={this.props.navigation.goBack.bind(this)} />
Refer to this point in the docs for overall methodology / cleaner code:
https://facebook.github.io/react/docs/handling-events.html
Upvotes: 0