React Native自定义Drawer侧栏跳转报navigate未定义错误如何解决
问题原因及修复方案
错误1:未从组件props中获取navigation对象
你在CustomSidebarMenu组件中直接调用了navigation.navigate,但navigation并没有被定义,它是父组件传递过来的props中的属性,需要先从props中取出。
错误2:navigate方法的路由参数格式错误
navigation.navigate的第一个参数需要是字符串格式的已注册路由名,你写的Profile没有加引号,会被识别为未定义的变量。
错误3:JSX语法错误
你写的点击事件代码括号未闭合,onPress={() => navigation.navigate(Profile) >My Profile</Text>缺少了事件回调的闭合括号。
其他潜在问题
- 代码中使用了
FontAwesome图标但未导入对应依赖,运行时也会报错 - 当前
App.js中仅注册了Landing Page一个抽屉路由,未注册Profile对应的路由,修复后跳转也会提示找不到路由
修复后的代码示例
component/MenuPage.js 调整部分
// 顶部先导入FontAwesome(需先安装react-native-vector-icons依赖) import FontAwesome from 'react-native-vector-icons/FontAwesome'; const CustomSidebarMenu = (props) => { // 新增:从props中取出navigation对象 const { navigation } = props; return ( // 原有代码不变... <View style={[styles.customItem]}> <Text style={{marginRight:10,}}> <FontAwesome name="user" style={[styles.MenuIcon, styles.VectorIconWhiteColor]}/> </Text> {/* 修正路由参数、语法、navigation调用 */} <Text style={[styles.WhiteColor]} onPress={() => navigation.navigate('Profile')}>My Profile</Text> </View> // 原有代码不变... ); };
App.js 调整部分
<Drawer.Navigator // 原有配置不变 > <Drawer.Screen name="Landing Page" component={AllScreenStack} // 原有配置不变 /> {/* 新增Profile路由注册,component替换为你自己的Profile页面组件 */} <Drawer.Screen name="Profile" component={你的Profile页面组件} /> </Drawer.Navigator>
内容的提问来源于stack exchange,提问作者user2995192
相关产品推荐
相关产品推荐

