logo
AI对话
AI写作
AI学术
AI绘画
知识社区

在React Native中获取当前页面名称的简单方法

此对话是使用 海鲸AI 创建的 • 发布时间:2025年03月24日 22:41

react native 安装了@react-navigation 我现在想在组件里获取当前页面的名称 该如何做

复制问题

在 React Native 中获取当前页面名称

在使用 React Navigation 的 React Native 应用中,你可以通过多种方式获取当前页面的名称。以下是几种常用方法:

1. 使用 useRoute hook

import { useRoute } from '@react-navigation/native';

function MyComponent() {
  const route = useRoute();
  const currentRouteName = route.name;
  
  console.log('当前页面名称:', currentRouteName);
  
  return (
    // 你的组件内容
  );
}

2. 使用 navigation prop

如果你的组件已经通过导航器接收了 navigation prop,可以这样做:

function MyComponent({ navigation }) {
  const currentRouteName = navigation.getCurrentRoute()?.name;
  
  console.log('当前页面名称:', currentRouteName);
  
  return (
    // 你的组件内容
  );
}

3. 通过 NavigationContainer 监听

在应用的根组件,你可以在 NavigationContainer 中设置监听器:

import { NavigationContainer } from '@react-navigation/native';
import { useRef } from 'react';

export default function App() {
  const navigationRef = useRef();
  const routeNameRef = useRef();

  return (
    <NavigationContainer
      ref={navigationRef}
      onReady={() => {
        routeNameRef.current = navigationRef.current.getCurrentRoute().name;
      }}
      onStateChange={() => {
        const currentRouteName = navigationRef.current.getCurrentRoute().name;
        routeNameRef.current = currentRouteName;
      }}
    >
      {/* 你的导航器 */}
    </NavigationContainer>
  );
}

然后你可以创建一个自定义的hook或者context来在应用的任何地方访问当前路由名称。

注意事项

  • 确保你已经正确安装了 @react-navigation/native 包
  • 对于嵌套导航器,获取到的是最深层级的当前活动路由名称
  • useRoute hook 只能在已经被导航器包裹的组件中使用

选择最适合你应用结构的方法即可获取当前页面名称。

重新生成
语音播放
复制回答