You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 15:45:01