问题
I have a back button that takes the user a screen back, but when there are no screens left to go back, I want it to do something else so this is my code:
<Button onPress={()=>{
if(CanGoBack){ // imaginary 'CanGoBack' variable
this.props.navigation.goBack()
}else{
this.doSomething()
}
}}/>
how can I achieve this?
回答1:
There is a function in this.props.navigation
called dangerouslyGetParent
. You can see it in the documentation here.
It states the following in the documentation:
Another good use case for this is to find the index of the active route in the parent's route list. So in the case of a stack if you are at index 0 then you may not want to render a back button, but if you're somewhere else in the list then you would render a back button.
So we can using the following to get the index of the route
this.props.navigation.dangerouslyGetParent().state.index
So we could use this in the onPress
of your Button
in the following way to check if we are back at the start of the route.
<Button onPress={() => {
// get the index of the route
let index = this.props.navigation.dangerouslyGetParent().state.index;
// handle the index we get
if (index > 0) {
this.props.navigation.goBack();
} else {
this.doSomething();
}
}}/>
回答2:
There is a canGoBack()
event. I am using React Navigation 5. Though I can't find it in the documentations. to check do console.log(this.props.navigation)
.
<Button onPress={()=>{
if(this.props.navigation.canGoBack()){
this.props.navigation.goBack()
}else{
this.doSomething()
}
}}/>
回答3:
On React navigation 5, there is a canGoBack()
function which is super helpful in this case.
来源:https://stackoverflow.com/questions/54700512/how-to-check-if-goback-function-is-doable-in-react-navigation