我有一个自定义导航栏,位于我的AppContainer旁边,我想根据导航器的当前routeName进行一些逻辑处理,我该怎么做?
我尝试通过导航作为参考,如此处https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html所述,但在该导航道具中,我没有当前路线名称。
const [navigation, setNavigation] = useState(null);
<AppContainer ref={nav => setNavigation(nav)} />
<NavBar navigation={navigation} />
const NavBar = ({ navigation }) => {
return <div>{navigation.state.routeName}</div>
};
// routeName is undefined
您可以像下面那样获得导航器对象的当前routeName
:
const {state: {routes, index}} = navigation;
const currentRouteName = routes[index];
实际上,导航器对象的所有路径都在routes
属性中,该属性是您在创建导航器时定义的; index
属性是应用程序最近导航到该索引的routes
中的索引号。
注意如果您当前的routes[index]
本身是内部导航器(例如抽屉导航器中的stackNavigator),则应该在内部导航器上执行上述操作,以达到应用程序当前已导航到它的真实routeName。
但是看来您的情况并不复杂,只需将上述代码仅在navigation
对象上应用一次即可获得所需的routeName。