点击DrawerNavigator头部按钮调用openDrawer时navigation未定义如何解决
问题原因
- 你当前将
screenOptions定义为静态对象,没有接收React Navigation自动注入的navigation上下文参数 - 代码中调用的
navigation.openDrawer()里的navigation变量未在当前作用域声明,因此返回undefined
解决方法
将screenOptions修改为函数形式,该函数会自动接收navigation、route两个注入参数,可直接拿到navigation对象调用openDrawer方法。
修改后的代码片段
import React from 'react'; import {View, TouchableOpacity} from 'react-native'; import {createDrawerNavigator} from '@react-navigation/drawer'; import Icon from 'react-native-vector-icons/Ionicons'; import {dimensions} from '../../constants/utils'; import CustomDrawerContent from './components/CustomDrawerContent'; const Drawer = createDrawerNavigator(); const DrawerNavigator = () => { const screenOptionsProps = { // 改为函数形式,接收navigation参数 screenOptions: ({navigation}) => ({ headerLeft: props => ( <View> <TouchableOpacity onPress={() => navigation.openDrawer()}> <Icon name="reorder-three-sharp" size={dimensions.width * 0.08} {...props} /> </TouchableOpacity> </View> ), }), }; return ( <Drawer.Navigator {...screenOptionsProps} drawerContent={props => <CustomDrawerContent {...props} />}> <Drawer.Screen name="Dashboard" component={Dashboard} /> </Drawer.Navigator> ); }; export default DrawerNavigator;
备选方案
如果需要更灵活的调用,也可以把头部按钮抽成独立组件,使用useNavigation hook获取导航对象(注意useNavigation需要从@react-navigation/native包导入):
// 抽离独立按钮组件 const HeaderMenuButton = (props) => { const navigation = useNavigation(); return ( <View> <TouchableOpacity onPress={() => navigation.openDrawer()}> <Icon name="reorder-three-sharp" size={dimensions.width * 0.08} {...props} /> </TouchableOpacity> </View> ) } // screenOptions 中直接引用组件 screenOptions: { headerLeft: props => <HeaderMenuButton {...props} /> }
内容的提问来源于stack exchange,提问作者jeet
相关产品推荐
相关产品推荐

