简体   繁体   中英

How to Add Logout Button In Drawer in React Native

I am Trying To Add Logout Button In My Drawer Screen. I know logout logic but I do not know where to Add It. please help. when user press on that logout I just want to open alert box with cancel and confirm button when user click on cancel. user will stay on screen where they are.

here is my App.js

const Drawer = createDrawerNavigator();

function MyDrawer({ navigation, route }) {
  return (
    <Drawer.Navigator initialRouteName="homeScreen">
      <Drawer.Screen
        name="logOut"
        component={logOut}
        options={{ drawerLabel: "Log Out" }}
      />
    </Drawer.Navigator>
  );
}

here is logout code

Alert.alert(
     "Logout",
    "Are you sure? You want to logout?",
     [
      {
        text: "Cancel",
       onPress: () => {
           return null;
         },
      },
       {
        text: "Confirm",
       onPress: () => {
          AsyncStorage.clear();
          props.navigation.replace("loginScreen");
        },
      },
    ],
    { cancelable: false }
   );

First import DrawerContentScrollView , DrawerItemList , and DrawerItem from @react-navigation/drawer:

import { 
  createDrawerNavigator, DrawerContentScrollView,
  DrawerItemList, DrawerItem
} from '@react-navigation/drawer';

To add non-screen buttons to your drawer, you need to customize your render of the Drawer. Do this by using drawerContent on Drawer.Navigator

<Drawer.Navigator drawerContent={props=><AppDrawerContent {...props} />} >
  {/*your screens here*/}
  <Drawer.Screen name="Login" component={Login} /> 
  <Drawer.Screen name="Home" component={Home} />
  <Drawer.Screen name="Signup" component={Signup} />
  {/*No need to create a screen just to log out, create a DrawerItem to do that*/}
</Drawer.Navigator>
 </NavigationContainer>

Now create your drawer render-er AppDrawerContent :

function AppDrawerContent(props){
   return (
      <DrawerContentScrollView {...props} contentContainerStyle={{flex:1}}>
        {/*all of the drawer items*/}
        <DrawerItemList {...props}  style={{borderWidth:1}}/>
        <View style={{flex:1,marginVertical:20,borderWidth:1}}>
          {/* here's where you put your logout drawer item*/}
          <DrawerItem 
            label="Log out"
            onPress={()=>{
              AsyncStorage.clear();
              props.navigation.replace("loginScreen");
            }}
            style={{flex:1,justifyContent:'flex-end'}}
          />
        </View>
      </DrawerContentScrollView>
    );
  }

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