React Native调用navigation.openDrawer()报undefined错误如何解决
错误原因排查
1. 导航对象取值错误
你定义AccountStack =(navigation)=>时,入参是组件的完整props对象,并不是navigation本身,navigation是props下的一个属性,你直接调用navigation.openDrawer()相当于在props根对象上找方法,自然不存在。
如果要从组件props里取navigation,应该改为解构取值:
export default AccountStack =({navigation})=>(
仅改这一点还不能解决问题,还存在后续错误。
2. Stack.Screen的options配置方式错误
你直接在options对象里调用外部的navigation,拿到的并不是Stack.Screen内部可用的导航对象,要在options里获取当前路由的导航对象,必须用函数形式返回配置:
<Stack.Screen name="Account" component={Account} options={({navigation}) => ({ headerRight: () => ( <Ionicons.Button name="reorder-three" color={"#FF0000"} size={40} backgroundColor={"none"} onPress={() => navigation.openDrawer()} /> ) })} />
3. 导航层级不匹配
你当前App.js的Drawer导航器根本没有注册AccountStack作为路由页面,AccountStack不在Drawer的导航层级内,就算拿到了正确的navigation对象,这个对象也属于Stack导航器实例,本身就没有openDrawer方法。
你需要先把AccountStack添加到Drawer的屏幕列表中:
// App.js 首先引入AccountStack import AccountStack from './AccountScreen'; // 然后在Drawer.Navigator下添加对应路由 <Drawer.Screen name="Account" component={AccountStack} />
兼容方案:跨层级调用Drawer
如果你的Stack确实要嵌套在Drawer的某一个子页面内部,可以直接用useNavigation钩子配合Drawer动作触发,不需要依赖当前导航对象的内置方法:
// 顶部引入依赖 import { useNavigation, DrawerActions } from '@react-navigation/native'; // 调整headerRight的逻辑 headerRight: () => { const navigation = useNavigation(); return ( <Ionicons.Button name="reorder-three" color={"#FF0000"} size={40} backgroundColor={"none"} onPress={() => navigation.dispatch(DrawerActions.openDrawer())} /> ) }
内容的提问来源于stack exchange,提问作者Onkar Mehra
相关产品推荐
相关产品推荐

