简体   繁体   中英

How to solve Custom Drawer Component Touchable onPress Screen switching not Working in React-Native?

In my react-native project, I am using one Drawer navigation where I have added two drawer items, which are working well by pressing. Below the Items I have declared one TouchableOpacity and inside that I have added one Text "log out". Now, by pressing the Logout I want change the screen to loginScreen and set the AsyncStorage value of token to empty string.

Here's a Screen Shot of my Drawer navigation-

在此处输入图片说明

And here's the code of my Drawer navigation component-

const CustomDrawerContentComponent = props => (
  <ScrollView>
    <SafeAreaView
      style={styles.container}
      forceInset={{ top: 'always', horizontal: 'never' }}>
      <DrawerItems {...props} />

    <TouchableOpacity
        onPress={() => {this.props.navigation.navigate('LoginScreen');
            {
            AsyncStorage.setItem("token", '')
            }

          }
        }
    >


     <Text>Log out</Text>

</TouchableOpacity>

    </SafeAreaView>
  </ScrollView>
);

const navigator = createDrawerNavigator(
  {
    NoteMeHome,
    MakeNote,


  },
  {
    drawerType: 'back',
    drawerPosition: 'right',
    drawerWidth: 200,
    drawerBackgroundColor: 'orange',
    contentComponent: CustomDrawerContentComponent
  }
);

So, After running the project whenever I press the log out Text it shows the following error-

在此处输入图片说明

So, it would be very nice if somebody helps me find out the problem and help to solve this.

Remove the 'this' and pass the props to the component when you call it or create your component as a class instead of a functional component and in the constructor pass the props, like:

constructor(props){
    super(props)
}

so the props will be accessible by this.props...

Replace:

contentComponent: CustomDrawerContentComponent

With:

contentComponent:(props)=> <CustomDrawerContentComponent navigation={this.props.navigation}/>

There is another solution:

You can easily export your CustomDrawerContentComponent and when you export it, wrap it with withNavigation from 'react-navigation' wrapper like that

import { withNavigation } from 'react-navigation';
    your code here ...
export default withNavigation(CustomDrawerContentComponent)

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