我有一个后退按钮,用户可以返回一个屏幕,但是当没有屏幕可以返回时,我希望它能做其他事情,所以这是我的代码:
<Button onPress={()=>{
if(CanGoBack){ // imaginary 'CanGoBack' variable
this.props.navigation.goBack()
}else{
this.doSomething()
}
}}/>
我该怎么做到这一点?
this.props.navigation
中有一个叫做dangerouslyGetParent
的函数。你可以在文档here中看到它。
它在文档中声明了以下内容:
另一个很好的用例是在父路由列表中找到活动路由的索引。因此,如果您在索引0处于堆栈的情况下,那么您可能不想渲染后退按钮,但如果您在列表中的其他位置,那么您将渲染后退按钮。
所以我们可以使用以下方法来获取路线的索引
this.props.navigation.dangerouslyGetParent().state.index
因此,我们可以通过以下方式在onPress
的Button
中使用它来检查我们是否回到了路线的起点。
<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();
}
}}/>