我有一个后退按钮,可以让用户返回一个屏幕,但当没有屏幕可供返回时,我希望它做其他事情,所以这是我的代码:
<Button onPress={()=>{
if(CanGoBack){ // imaginary 'CanGoBack' variable
this.props.navigation.goBack()
}else{
this.doSomething()
}
}}/>
我怎样才能做到这一点?
我有一个后退按钮,可以让用户返回一个屏幕,但当没有屏幕可供返回时,我希望它做其他事情,所以这是我的代码:
<Button onPress={()=>{
if(CanGoBack){ // imaginary 'CanGoBack' variable
this.props.navigation.goBack()
}else{
this.doSomething()
}
}}/>
我怎样才能做到这一点?
注意:这个答案最初是为
react-navigation
v3.3.0
写的.您应该查看当前文档中的react-navigation
条,以确保仍然支持该方法,以及是否有任何更改/更简单的方法.
this.props.navigation
中有一个函数叫做dangerouslyGetParent
.
它在第documentation条中陈述了以下内容:
另一个很好的用例是找到活动对象的索引
所以我们可以使用下面的方法来获得路由的索引
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();
}
}}/>
从documentation中,我们可以看到dangerouslyGetParent
仍然存在.
此方法从父导航器返回导航props
因此,在v5中对v3使用上述方法是可能的.
还有一个名为canGoBack()
的未记录api.这可以通过以下方式从导航props 访问:
this.props.navigation.canGoBack()
如果可以返回堆栈,则此属性将返回布尔值.这意味着我们可以通过以下方式更新我们为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,它很容易更改,因此依赖它可能会有风险.