我正在使用此https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html从任何来源访问导航,我的文件如下:
import { createRef } from 'react';
export const navigationRef = createRef();
export function navigate(name, params) {
return navigationRef.current?.navigate(name, params);
}
export function goBack() {
return navigationRef.current?.goBack();
}
export function getRootState() {
return navigationRef.current?.getRootState();
}
这非常适合我的@navigation/drawer
,它在我的堆栈导航之外。
只有一个问题,即最后一种方法未同步,我希望项目菜单上的活动状态为当前路线。
反应导航5怎么可能?
答案 0 :(得分:4)
我正在使用以下方法在react-navigation v5中获取当前路线名称。 https://reactnavigation.org/docs/navigation-prop/#dangerouslygetstate
const {index, routes} = this.props.navigation.dangerouslyGetState();
const currentRoute = routes[index].name;
console.log('current screen', currentRoute);
答案 1 :(得分:3)
NavigationContainer具有onStateChange属性,在这种情况下非常有用,请检查react-navigation文档Screen Tracking for analytics,如果您需要不带导航属性的访问权限,请参见Navigating without the navigation prop
我共享代码以仅获取活动的routeName
function App(){
const routeNameRef = React.useRef();
// Gets the current screen from navigation state
const getActiveRouteName = (state)=> {
const route = state.routes[state?.index || 0];
if (route.state) {
// Dive into nested navigators
return getActiveRouteName(route.state);
}
return route.name;
};
return (<NavigationContainer
onStateChange={(state) => {
if (!state) return;
//@ts-ignore
routeNameRef.current = getActiveRouteName(state);
}}
>
...
</NavigationContainer>)
}
答案 2 :(得分:1)
如果您想从组件中了解当前屏幕,也可以使用以下方法:
export const HomeScreen = ({ navigation, route }) => {
console.log(route.name);
return (
{...}
);
};
答案 3 :(得分:0)
这对我有用。在navigationRef.js
let navigator;
export const setNavigator = (nav) => {
navigator = nav;
};
export const getCurrentRoute = () => {
const route = navigator.getCurrentRoute();
return route.name;
};
可以从任何这样的来源引用
import { getCurrentRoute } from '../navigationRef';
const currentScene = getCurrentRoute();
答案 4 :(得分:0)
可以从附加到导航容器的 navigationRef 中获取。其中 navigationRef 是一个引用。
export const navigationRef = React.createRef()
和
<NavigationContainer
ref={navigationRef}
>
<Navigator />
</NavigationContainer>
然后使用:const currentRouteName = navigationRef.current.getCurrentRoute().name
获取当前路由名称。
或者在功能组件中,您可以使用Ref const navigationRef = React.useRef()
答案 5 :(得分:0)
the docs 推荐了一个名为 getFocusedRouteNameFromRoute(route)
的实用函数。
但是 - 它似乎只适用于子屏幕,所以我定义了以下函数来获取活动路由名称:
const getCurrentRouteName = (navigation, route) => {
if (route.state)
return getFocusedRouteNameFromRoute(route);
return route.name;
};