微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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>
    );
  }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。