React Native Navigation:头部按钮打开抽屉导航报undefined错误求助
嘿,这个问题我太熟了!你遇到的undefined is not an object (evaluating '_this.props.navigate')错误,核心原因是在navigationOptions里错误地使用了this.props.navigation——这里的上下文并不是组件实例,所以this根本拿不到props里的导航对象。
错误原因拆解
你在navigationOptions里已经通过解构拿到了navigation参数:
navigationOptions: ({ navigation }) => ({ ... })
但在按钮的onPress里却用了this.props.navigation.openDrawer(),这就导致找不到对应的导航对象,自然报错。
修正后的代码
直接使用解构出来的navigation对象调用openDrawer()就行,修改后的完整代码如下:
import React, { Component } from 'react'; import { View } from 'react-native'; // 补上你之前漏导的View组件 import { createStackNavigator, NavigationActions } from 'react-navigation' import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import { Draw } from './DrawNav.js' export const RootStack = createStackNavigator ( { DrawNav: { screen: Draw, navigationOptions: ({ navigation }) => ({ //Hide the shadow of the header headerStyle: { elevation:0, shadowColor: 'transparent', shadowRadius: 0, shadowOffset: { height: 0, } }, headerLeft: ( <View style={{marginLeft: 10}}> <Icon name="menu" size={25} color="#D4AF37" onPress={() => navigation.openDrawer()} /> </View> ), }) }, }, );
补充说明
React Navigation完全支持从Stack导航的头部按钮打开抽屉导航,只要正确使用navigation对象就行。navigation参数在navigationOptions里是直接可用的,不用再从this.props里取。
内容的提问来源于stack exchange,提问作者jrocc
相关产品推荐
相关产品推荐

