1

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.

1
  • The fat arrow is preserving the this context. Commented Aug 9, 2017 at 19:04

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

No problem. Glad to help!
it is unfortunate that they didn't mention in the doc that goBack is expecting undefined
0

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

2 Comments

I think that goBack is itself an arrow function, and therefore cannot be rebound to a new this.
yeah i think so too ^. you can create a variable that's referencing an anonymous function and can pass that function as this.foo and it gets invoked properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.