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

React Navigation v6:如何在深层嵌套页面禁用左侧抽屉?

在React Navigation v6中深层路由禁用Drawer头部的解决方案

要在嵌套层级最深的RlsACOptionsComponent页面中禁用Drawer的头部(隐藏汉堡按钮、禁止侧滑打开Drawer),可以通过递归获取焦点路由的方式,让Drawer导航器感知到深层路由状态,具体实现如下:

1. 导入必要工具函数

首先从@react-navigation/native导入getFocusedRouteNameFromRoute,用于获取当前焦点路由名称:

import { getFocusedRouteNameFromRoute } from '@react-navigation/native';

2. 编写递归获取深层焦点路由的辅助函数

这个函数会逐层遍历嵌套的导航路由,直到找到最底层的焦点路由:

const getDeepestFocusedRouteName = (route) => {
  const currentRouteName = getFocusedRouteNameFromRoute(route);

  // 如果当前路由存在嵌套的子路由,继续递归查找
  if (currentRouteName && route.state?.routes) {
    // 获取当前激活的子路由
    const activeChildRoute = route.state.routes[route.state.index];
    return getDeepestFocusedRouteName(activeChildRoute);
  }

  return currentRouteName;
};

3. 在Drawer导航器中根据深层路由配置选项

修改DrawerNavigation中的Drawer.Screen,通过options函数动态判断当前深层路由,从而控制Drawer的头部显示和手势锁定:

const DrawerNavigation = (props: Props) => {
  const Drawer = createDrawerNavigator();

  return (
    <Drawer.Navigator
      useLegacyImplementation
      initialRouteName="GlobalTabNavigation"
    >
      <Drawer.Screen
        name="GlobalTabNavigation"
        component={BottomTabNavigation}
        options={({ route }) => {
          const deepestRouteName = getDeepestFocusedRouteName(route);
          
          return {
            // 当处于RlsACOptions页面时,隐藏Drawer的头部
            headerShown: deepestRouteName !== 'RlsACOptions',
            // 锁定Drawer侧滑手势,禁止打开
            drawerLockMode: deepestRouteName === 'RlsACOptions' ? 'locked-closed' : 'unlocked',
          };
        }}
      />
    </Drawer.Navigator>
  );
};

补充说明

  • drawerLockMode: 'locked-closed'会完全禁止侧滑打开Drawer,同时如果Drawer头部有汉堡按钮,也会因为headerShown: false而隐藏,实现“完全禁用Drawer头部”的需求。
  • 这种递归方式支持任意层级的嵌套导航,无论后续新增多少层嵌套路由,只要目标页面的路由名称不变,就能正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:05:29