如何检查goBack()函数在反应导航中是否可行?

问题描述 投票:3回答:1

我有一个后退按钮,用户可以返回一个屏幕,但是当没有屏幕可以返回时,我希望它能做其他事情,所以这是我的代码:

<Button onPress={()=>{
   if(CanGoBack){ // imaginary 'CanGoBack' variable
     this.props.navigation.goBack()
   }else{
     this.doSomething()
   }
}}/>

我该怎么做到这一点?

javascript react-native react-navigation
1个回答
4
投票

this.props.navigation中有一个叫做dangerouslyGetParent的函数。你可以在文档here中看到它。

它在文档中声明了以下内容:

另一个很好的用例是在父路由列表中找到活动路由的索引。因此,如果您在索引0处于堆栈的情况下,那么您可能不想渲染后退按钮,但如果您在列表中的其他位置,那么您将渲染后退按钮。

所以我们可以使用以下方法来获取路线的索引

this.props.navigation.dangerouslyGetParent().state.index

因此,我们可以通过以下方式在onPressButton中使用它来检查我们是否回到了路线的起点。

<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();
  }
}}/>
© www.soinside.com 2019 - 2024. All rights reserved.