我想在react-navigation中获取当前路由或屏幕的名称,以便在if条件语句中使用并进行更改。
对于 react-navigation v5:
import { useRoute } from '@react-navigation/native';
const route = useRoute();
console.log(route.name);
您可以按以下代码进行捕获:
this.props.navigation.state.routeName
如果您正在使用嵌套导航器,可以使用以下代码获取当前活动屏幕的状态
import { NavigationState } from 'react-navigation';
const getActiveRouteState = function (route: NavigationState): NavigationState {
if (!route.routes || route.routes.length === 0 || route.index >= route.routes.length) {
return route;
}
const childActiveRoute = route.routes[route.index] as NavigationState;
return getActiveRouteState(childActiveRoute);
}
使用方法:
const activeRoute = getActiveRouteState(this.props.navigation.state);
当我需要从NavigationDrawer获取当前活动屏幕状态时,我使用这个。
react-navigation
导入的。 - gianlucaparadise在 react-navigation v5.x 中,这个很好用。
this.props.route.name
const routeNameRef = React.createRef();
<NavigationContainer
ref={navigationRef}
onReady={() => routeNameRef.current = navigationRef.current.getCurrentRoute().name}
onStateChange={() => {
const previousRouteName = routeNameRef.current
const currentRouteName = navigationRef.current.getCurrentRoute().name
if (previousRouteName !== currentRouteName) {
// Do something here with it
}
// Save the current route name for later comparision
routeNameRef.current = currentRouteName
}}
>
{/* ... */}
</NavigationContainer>
);
export function getCurrentRouteName(action) {
return routeNameRef;
}
您可以导入 getCurrentRouteName 函数并使用它来获取当前路由名称,这适用于 React Navigation 5 中的任何嵌套导航器。
在使用 "react-navigation": "^3.0.8"
和 DrawerNavigator 时,可以通过 this.props.activeItemKey
从 this.props
对象中访问它。
import {getFocusedRouteNameFromRoute,useRoute} from '@react-navigation/native';
//...
const route = useRoute();
const routeName = getFocusedRouteNameFromRoute(route); // Get Nested Route Name
import { useNavigationState } from '@react-navigation/native'
const routes = useNavigationState(state => state.routes)
const currentRoute = routes[routes.length - 1].name
console.log('currentRoute: ', currentRoute)
注册NavigationService.js
,详细文档请查看没有导航属性的导航
<App
ref={navigatorRef => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}
/>
递归函数
function getCurrentRoute(nav){
if(Array.isArray(nav.routes)&&nav.routes.length>0){
return getCurrentRoute(nav.routes[nav.index])
}else {
return nav.routeName
}
}
getCurrentRoute(NavigationService.getNavigator().state.nav)
可以通过与导航容器附加的 navigationRef 来获取此内容,其中 navigationRef
是一个引用。
export const navigationRef = React.createRef()
<NavigationContainer
ref={navigationRef}
>
<Navigator />
</NavigationContainer>
然后使用: const currentRouteName = navigationRef.current.getCurrentRoute().name
或者在函数式组件中,您可以使用useRef:const navigationRef = React.useRef()