【问题标题】:How to get current route name in react native using react navigation v5如何使用 React Navigation v5 在 React Native 中获取当前路由名称
【发布时间】:2020-09-28 12:23:27
【问题描述】:

我只想要 react-native 中当前路线或屏幕的名称,我可以在条件中使用它。我正在使用基于反应类的组件。

【问题讨论】:

    标签: reactjs react-native react-navigation


    【解决方案1】:

    保留导航容器的引用,然后在引用上调用getCurrentRoute().name

    class App {
      navigationRef = null
    
      render() {
        <NavigationContainer ref={ref => this.navigationRef = ref}>
           .....
        </NavigationContainer>
      }
    
      getCurrentRouteName() {
        return this.navigationRef.getCurrentRoute().name
      }
    }
    

    来源:https://reactnavigation.org/docs/screen-tracking/(我只是将基于函数的组件语法转换为等效的类组件一)

    【讨论】:

    • 这对我有用,但它对性能有很大的影响。切换标签/屏幕几乎是瞬间完成的,而不是一秒钟多一点。
    • 更新:延迟是由使用 Context API 设置全局状态引起的,不是路由器问题。
    【解决方案2】:

    在路由道具中有一个name 属性。

    function ProfileScreen({ route }) {
      return (
        <View>
          <Text>This is the profile screen of the app</Text>
          <Text>{route.name}</Text>
        </View>
      );
    }
    

    来源:https://reactnavigation.org/docs/route-prop

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 2017-11-07
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 2020-05-23
      • 2015-07-14
      相关资源
      最近更新 更多