You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native的Drawer.Navigator中添加退出登录按钮并跳转登录页

解决方案

你跳转失败的核心原因有两个:

  1. 你给Drawer导航包裹的NavigationContainer加了independent={true}属性,该属性会让当前导航容器完全独立,和上层导航栈隔离,无法调用上层导航的跳转方法
  2. 你当前的Drawer.Navigator中只注册了3个业务页面,没有将Login页面纳入当前导航栈的路由配置中,导航自然找不到对应的Login页面

你可以根据自己的业务架构选择下面任意一种方案实现:


方案1:Login页在上层导航栈(推荐,符合常规登录态管理逻辑)

绝大多数项目都会在外层套一个Stack导航,放置Login、Drawer容器这类全局页面,你可以按如下修改:

  • 先移除DrawerSetting文件中NavigationContainer的independent={true}属性,让当前抽屉导航和上层导航栈连通
  • 直接在CustomSidebarMenu的logout方法中调用跳转即可,跳转时建议同时清理本地存储的用户登录态(比如token、用户信息等)
function logout(){
    // 清理登录态代码可加在这里
    props.navigation.navigate("Login");
}

方案2:Login页放在当前抽屉导航栈内

如果你不需要上层导航栈,想把Login页直接纳入当前抽屉导航的路由管理:

  • 第一步:在Drawer.Navigator中新增Login页面的注册配置,通过drawerItemStyle配置隐藏侧边栏的Login选项
<Drawer.Navigator initialRouteName="Resources" drawerContent={(props) => <CustomSidebarMenu {...props} />}>
    <Drawer.Screen name="Resources" component={Resources}
        options={{ drawerLabelStyle: { fontSize: 16, color: 'black', } }}
    />
    <Drawer.Screen name="Themes" component={Themes}
        options={{ drawerLabelStyle: { fontSize: 16, color: 'black', } }}
    />
    <Drawer.Screen name="About Us" component={AboutUs}
        options={{ drawerLabelStyle: { fontSize: 16, color: 'black', } }}
    />
    {/* 新增Login页面配置 */}
    <Drawer.Screen name="Login" component={Login}
        options={{ 
            drawerLabelStyle: { fontSize: 16, color: 'black' },
            drawerItemStyle: { display: 'none' }
        }}
    />
</Drawer.Navigator>
  • 第二步:打开CustomSidebarMenu中logout方法的跳转注释即可
function logout(){
    alert("Hello");
    props.navigation.navigate("Login");
    // 如果你需要点击退出后直接关闭APP,再打开BackHandler的注释即可
    // BackHandler.exitApp();
}

内容的提问来源于stack exchange,提问作者Rakesh Saini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 04:36:03