簡體   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