javascript-如何在反应导航中检查goBack()函数是否可行?
作者:互联网
我有一个后退按钮,可以使用户返回屏幕,但是当没有屏幕可以返回时,我希望它做其他事情,所以这是我的代码:
<Button onPress={()=>{
if(CanGoBack){ // imaginary 'CanGoBack' variable
this.props.navigation.goBack()
}else{
this.doSomething()
}
}}/>
我该如何实现?
解决方法:
在this.props.navigation中有一个函数称为angerallyGetParent.您可以在文档here中看到它.
它在文档中指出以下内容:
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,react-native,javascript 来源: https://codeday.me/bug/20191108/2006550.html