我有一个后退按钮,可以让用户返回一个屏幕,但是当没有屏幕可以返回时,我希望它做些别的事情,所以这是我的代码:
<Button onPress={()=>{
if(CanGoBack){ // imaginary 'CanGoBack' variable
this.props.navigation.goBack()
}else{
this.doSomething()
}
}}/>
我怎样才能做到这一点?
最佳答案
Note this answer was originally written for
react-navigation
v3.3.0
. You should check the current documentation forreact-navigation
to make sure that this is still supported and if there are any changes/easier methods.
React-Navigation v3
this.props.navigation
中有一个名为dangerouslyGetParent
的函数。
它在 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.
所以我们可以使用下面的方法来获取路由的索引
this.props.navigation.dangerouslyGetParent().state.index
所以我们可以在您的 Button
的 onPress
中使用它以下列方式检查我们是否回到了路线的起点。
<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();
}
}}/>
React-Navigation v5 更新
来自documentation ,我们可以看到 dangerouslyGetParent
仍然存在。
This method returns the navigation prop from the parent navigator that the current navigator is nested in. For example, if you have a stack navigator and a tab navigator nested inside the stack, then you can use dangerouslyGetParent inside a screen of the tab navigator to get the navigation prop passed from the stack navigator.
所以可以在v5中对v3使用上述方法。
v5 中的 canGoBack()
还有一个未记录的 api,称为 canGoBack()
。这可以通过以下方式从导航 Prop 访问:
this.props.navigation.canGoBack()
如果您能够返回堆栈,此属性将返回一个 bool 值。这意味着我们可以通过以下方式更新我们为 v3
所做的代码。
<Button onPress={() => {
// check to see if it is possible to go back
let canGoBack = this.props.navigation.canGoBack();
// handle what we do it we can/cannot go back
if (canGoBack) {
this.props.navigation.goBack();
} else {
this.doSomething();
}
}}/>
但是,由于这是一个未记录的 API,它很可能会更改,因此依赖它可能会有风险。
v6 中的 canGoBack()
现在看来 canGoBack
已经记录在案了,您可以找到信息 here
This method returns a boolean indicating whether there's any navigation history available in the current navigator, or in any parent navigators. You can use this to check if you can call
navigation.goBack()
:
if (navigation.canGoBack()) {
navigation.goBack();
}
Don't use this method for rendering content as this will not trigger a re-render. This is only intended for use inside callbacks, event listeners etc.
关于javascript - 如何检查 goBack() 函数在 react 导航中是否可行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54700512/