简体   繁体   中英

React Native - TypeError: undefined is not an object (evaluating 'navigation.toggleDrawer')

In my App project I am trying to create a button that if pushed opens the drawer navigator (look at the toDrawerButton component in the code below). My problem is that when pushing this button I get the following error:

TypeError: undefined is not an object (evaluating 'navigation.toggleDrawer')

this is because this.props is a void object (Object {}) and then this.props.navigation is undefined.

How can I solve this issue and get my this.props object not anymore void?? Thanks!

 import React, {Component} from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import { createDrawerNavigator } from '@react-navigation/drawer'; import Menu from './MenuComponent'; import Home from './HomeComponent'; import {Icon, Button} from 'react-native-elements'; const toDrawerButton = ({ headerLeft: ({navigation}) => (<Button icon = {<Icon name='menu' size={24} color='black' onPress={() => navigation.toggleDrawer()}/>} />)}); // each choiche in the DrawerNavigator will have a stack hiarerchy, this is why for // each of them I define a stackNavigator (even if with just one screen at the moment) ------------------ const MenuNavigator = createStackNavigator(); const MenuNavigatorScreens = () => ( <MenuNavigator.Navigator initialRouteName="Menu"> <MenuNavigator.Screen name = "Menu" component={Menu} options={toDrawerButton}/> </MenuNavigator.Navigator>); const HomeNavigator = createStackNavigator(); const HomeNavigatorScreens = () => ( <HomeNavigator.Navigator initialRouteName="Home"> <HomeNavigator.Screen name = "Home" component={Home} /> </HomeNavigator.Navigator>); // DrawerNavigator definition ------------------------------------ const DrawerNavigator = createDrawerNavigator(); const DrawerNavigatorScreens = () => ( <NavigationContainer> <DrawerNavigator.Navigator initialRouteName="Home"> <DrawerNavigator.Screen name = "Home" component={HomeNavigatorScreens}/> <DrawerNavigator.Screen name = "Menu" component={MenuNavigatorScreens}/> </DrawerNavigator.Navigator> </NavigationContainer>); class MainNavigator extends Component { constructor(props) { super(props); } render(){ return (<DrawerNavigatorScreens/>) } }; export default MainNavigator;

You should change toDrawerButton to this:

const toDrawerButton = ({navigation})=>({
    headerLeft: () =>
            (<Button
            icon = {<Icon name='menu' size={24}
                    color='black'
                    onPress={() => navigation.toggleDrawer()}/>}
            />)});
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM