繁体   English   中英

如何在 React Native 的抽屉中添加注销按钮

[英]How to Add Logout Button In Drawer in React Native

我正在尝试在我的抽屉屏幕中添加注销按钮。 我知道注销逻辑,但我不知道在哪里添加它。 请帮忙。 当用户按下该注销时,我只想在用户单击取消时打开带有取消和确认按钮的警报框。 用户将留在他们所在的屏幕上。

这是我的 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>
  );
}

这是注销代码

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 }
   );

首先从@react-navigation/drawer 导入DrawerContentScrollViewDrawerItemListDrawerItem

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

要将非屏幕按钮添加到您的抽屉,您需要自定义抽屉的渲染。 通过在drawerContent上使用抽屉内容来做到这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>

现在创建您的抽屉渲染器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>
    );
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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