如何在 React Native 的抽屉中添加注销按钮
Posted
技术标签:
【中文标题】如何在 React Native 的抽屉中添加注销按钮【英文标题】:How to Add Logout Button In Drawer in React Native 【发布时间】:2021-08-23 06:51:29 【问题描述】:我正在尝试在我的抽屉屏幕中添加注销按钮。我知道注销逻辑,但我不知道在哪里添加它。请帮忙。当用户按下该注销时,我只想在用户单击取消时打开带有取消和确认按钮的警报框。用户将留在他们所在的屏幕上。
这是我的 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
);
【问题讨论】:
【参考方案1】:首先从@react-navigation/drawer 导入DrawerContentScrollView
、DrawerItemList
和DrawerItem
:
import
createDrawerNavigator, DrawerContentScrollView,
DrawerItemList, DrawerItem
from '@react-navigation/drawer';
要将非屏幕按钮添加到您的抽屉,您需要自定义抽屉的渲染。通过在Drawer.Navigator
上使用drawerContent
来做到这一点
<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>
);
【讨论】:
以上是关于如何在 React Native 的抽屉中添加注销按钮的主要内容,如果未能解决你的问题,请参考以下文章
在 react native 中构建自定义抽屉时,如何在抽屉项目上使用按钮/图标?
如何在 React Native Navigation wix V1 中单击时关闭抽屉