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

React Native(@react-navigation/drawer^5.11.4):自定义DrawerContent调用closeDrawer报错求助

解决React Navigation 5自定义DrawerContent中调用closeDrawer的问题

我来帮你搞定这个问题!你遇到的报错undefined is not an object (evaluating 'props.naviagtion.closeDrawer')(注意这里还有个拼写错误:naviagtion应该是navigation),核心原因是自定义抽屉组件没有拿到正确的navigation实例。

问题根源

在你的MyDrawer组件里,drawerContent的写法是:

drawerContent={() => <DrawerNavigation {...props} />}

这里传递给DrawerNavigation的props是MyDrawer组件自身的props,并不是React Navigation为抽屉内容提供的包含navigation的专属props。React Navigation的drawerContent回调会自动传入一个包含navigation、state等关键属性的对象,你需要把这个对象传给自定义抽屉组件。

修复步骤

  1. 修改Drawer.Navigator的drawerContent,将回调接收的参数传递给DrawerNavigation
  2. 确保调用closeDrawer()时拼写正确(避免naviagtion这类笔误)

修复后的完整代码

function DrawerNavigation(props) {
  // 这里的props现在包含正确的navigation实例了
  return (
    <DrawerContentScrollView {...props}>
      <TouchableOpacity 
        style={styles.colseIconContainer} 
        onPress={() => {
          // 确保拼写正确:navigation
          props.navigation.closeDrawer();
        }}
      >
        <IconButton icon={({size}) => (
          <Image source={require('../../../resource/images/CloseIcon.png')} style={{width: size, height: size}} />
        )} size={40} />
      </TouchableOpacity>
    </DrawerContentScrollView>
  );
}

const Drawer = createDrawerNavigator();
export default function MyDrawer(props) {
  return (
    <Drawer.Navigator 
      drawerPosition="right" 
      // 这里把drawerContent回调的参数(drawerProps)传给DrawerNavigation
      drawerContent={(drawerProps) => <DrawerNavigation {...drawerProps} />} 
      drawerStyle={styles.drawerStyle}
    >
      <Drawer.Screen name="Home" component={HomeScreen} options={{swipeEnabled: true}} />
      <Drawer.Screen name="Notifications" component={CommonUserComponent} />
    </Drawer.Navigator>
  );
}

额外说明

在React Navigation 5中,drawerContent回调接收的参数包含以下常用属性:

  • navigation: 抽屉的导航实例,可调用closeDrawer()、openDrawer()等方法
  • state: 抽屉的状态信息
  • descriptors: 屏幕的描述信息

通过传递这个参数,你的自定义抽屉组件就能正确访问到导航方法了。

内容的提问来源于stack exchange,提问作者Satyam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:30:01