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

问题描述

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...