React Native(@react-navigation/drawer^5.11.4):自定义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等关键属性的对象,你需要把这个对象传给自定义抽屉组件。
修复步骤
- 修改
Drawer.Navigator的drawerContent,将回调接收的参数传递给DrawerNavigation - 确保调用
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
相关产品推荐
相关产品推荐

