【问题标题】:Getting the current routeName in react navigation在反应导航中获取当前的 routeName
【发布时间】:2019-07-03 11:04:15
【问题描述】:

我想在 react navigator 中获取当前 routeName 的名称。我遇到了三种解决方案:

 1. const { routeName } = navigation.state.routes[navigation.state.index];

 2. this.props.navigation.state.RouteName

 3. const route = navigationState.routes[navigationState.index];

第一个似乎工作正常。对于第二个,我不确定如何使用它。第三个选项(如官方文档中给出的),生成错误 ReferenceError: navigationState is undefined.

请帮我找出在导航时找到活动屏幕名称的正确方法。

【问题讨论】:

    标签: react-native routes navigation state


    【解决方案1】:
    function getActiveRouteName(navigationState) {
      if (!navigationState) {
        return null
      }
      const route = navigationState.routes[navigationState.index]
      if (route.routes) {
        return getActiveRouteName(route)
      }
      return route.routeName
    }
    
    // Example Usage
    const currentScreen = getActiveRouteName(this.props.router);
    if (currentScreen === 'Login') {
       // do something
    }
    

    【讨论】:

    • 你能解释一下吗?
    • 可以看到,路由内部看起来像routes(an Array) + index(a number),所以你只需要通过routes[index]打开它(我们称之为路由A),如果你发现路由A仍然看起来像@ 987654324@里面,你需要反复打开,直到找到你需要的最深的路线。最深的路线没有路线作为其属性。
    猜你喜欢
    • 1970-01-01
    • 2018-08-20
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多