如何在 navigation.js 文件中的 react-navigation 中获取当前路由名称?

How to current route name in react-navigation inside navigation.js file?

我想知道当前的路由名称,但是在导航 js 文件中,我在任何组件中使用 useRoute 挂钩并且工作正常,但是当我在 navigation.js[=12] 中使用 useRoute 时出现此错误=]

错误:找不到路由对象。您的组件是否在导航器的屏幕内?

navigation.js 代码示例,

export default function Navigation() {
  const route = useRoute(); // show error >> Error: Couldn't find a route object. Is your component inside a screen in a navigator?
  
  return (
      <Stack.Navigator
        screenOptions={{
          headerShown: false,
        }}>
            <Stack.Screen name="HomeScreen" component={HomeScreen} />
      </Stack.Navigator>
  );
}

当我删除 useRoute 时,错误消失了,但我需要使用 useRoute 或任何其他方式在 navigation.js 文件中获取当前路由名称。

您可以将 navigationContainerRefNavigationContainer 传递到 Navigation 组件以使 navigation 对象可访问。

考虑以下代码片段。

import { createNavigationContainerRef } from "@react-navigation/native"

export const navigationRef = createNavigationContainerRef()

const App = () => {
    return <NavigationContainer
              ref={navigationRef}>
                 <Navigation navigation={navigationRef} />
            </NavigationContainer>  
}
export default App

然后,里面 Navigation.

export default function Navigation({ navigation }) {

  const route = navigation.current?.getCurrentRoute()
  
  return (
      <Stack.Navigator
        screenOptions={{
          headerShown: false,
        }}>
            <Stack.Screen name="HomeScreen" component={HomeScreen} />
      </Stack.Navigator>
  );
}

然后使用route?.name访问当前路由名称。

编辑: 正如 jhon antoy 在评论中正确指出的那样,如果我们导航到不同的屏幕,这不会更新当前的路由状态。我们需要自己更新如下。

export const navigationRef = createNavigationContainerRef();

const App = () => {
  const [routeName, setRouteName] = useState();

  return (
    <NavigationContainer
      ref={navigationRef}
      onReady={() => {
        setRouteName(navigationRef.getCurrentRoute().name)
      }}
      onStateChange={async () => {
        const previousRouteName = routeName;
        const currentRouteName = navigationRef.getCurrentRoute().name;
        console.log("route", currentRouteName)
        setRouteName(currentRouteName);
      }}
    >
       <Navigation routeName={routeName} />
    </NavigationContainer>
  );
}

export default App;

里面 Navigation.

export function Navigation(props) {

  const route = props.routeName

  console.log(props)

  return (
      <Stack.Navigator
        screenOptions={{
          headerShown: false,
        }}>
            <Stack.Screen name="HomeScreen" component={HomeScreen} />
      </Stack.Navigator>
  );
}

我做了一个snack with some simple navigation buttons.