预期行为:应打开一个抽屉,标题中包含菜单图标。
当前行为:错误消息undefined is not an object ('evaluating this.props.navigation')
搜索错误对我没有帮助。
我将导航拆分为两个文件:RootNavigation.js和MainTabNavigation
根导航.js
const AppNavigator = createSwitchNavigator({
Main: MainTabNavigator,
});
const DrawerStack = createDrawerNavigator({
Home: {
screen: AppNavigator
},
Login: {
screen: login
},
Signup: {
screen: signup
}
});
export default class RootNavigation extends React.Component {
componentDidMount() {
this._notificationSubscription = this._registerForPushNotifications();
}
主选项卡导航.js
const HomeStack = createStackNavigator({
Home: HomeScreen,
});
HomeStack.navigationOptions = {
tabBarLabel: 'Home',
tabBarIcon: ({ focused }) => (
<TabBarIcon
focused={focused}
name={
Platform.OS === 'ios'
? `ios-home${focused ? '' : '-outline'}`
: 'md-home'
}
/>
),
};
const LinksStack = createStackNavigator({
Links: LinksScreen,
});
LinksStack.navigationOptions = {
tabBarLabel: 'Shops',
tabBarIcon: ({ focused }) => (
<TabBarIcon
focused={focused}
name={Platform.OS === 'ios' ? `ios-list${focused ? '' : '-outline'}` : 'md-list'}
/>
),
};
const SettingsStack = createStackNavigator({
Settings: SettingsScreen,
});
SettingsStack.navigationOptions = {
tabBarLabel: 'Cart',
tabBarIcon: ({ focused }) => (
<TabBarIcon
focused={focused}
name={Platform.OS === 'ios' ? `ios-cart${focused ? '' : '-outline'}` : 'md-cart'}
/>
),
};
export default createBottomTabNavigator({
HomeStack,
LinksStack,
SettingsStack,
});
在标题中显示图标的MainTab文件
static navigationOptions = ({navigation}) =>({
title: 'Home',
headerLeft: <Ionicons
name="md-menu"
size={25}
color="blue"
style={{ margin: 7,}}
onPress={() => this.props.navigation.navigate('DrawerOpen')}
/>
});
如此处的文档中所述,当navigationOptions
用作函数时,this
不引用组件的实例;因此this.props
不可用。
相反,您需要替换:
this.props.navigation.navigate('DrawerOpen')
跟:
navigation.navigate('DrawerOpen')
或者,您可能希望使用navigation.openDrawer()
帮助程序,如此处的示例所示,因为导航到DrawerOpen
意味着您要导航到具有该名称的屏幕。
当你创建这样的组件女巫类时,你必须知道这一点
class MyComponent extends ....
如果你想使用任何道具,你必须写这个关键字,例如
this.props.navigation.nvigate()
但是如果你像这样使用箭头功能创建组件
const Mycomponent = (props) => {}
你不需要这个关键字,对于呼叫道具,你必须这样写
props.navigation.navigate()
在您的情况下,如果在导航选项中使用组件,则不需要这个或道具关键字,只需编写
navigation.navigate()