如何仅在Stack导航栈的部分页面锁定Drawer抽屉菜单滑动打开行为
两种实现方案,按需选用即可。
方案1:全局动态配置(推荐)
核心逻辑是让父级Drawer导航实时感知嵌套Stack内的当前活跃页面,匹配到需要禁用手势的页面时,自动关闭抽屉滑动唤起能力。
直接修改DrawerMenu组件代码:
import { useNavigationState } from '@react-navigation/native'; const DrawerMenu = () => { // 递归获取当前最内层聚焦的页面路由名 const currentRouteName = useNavigationState(state => { let activeRoute = state.routes[state.index]; while (activeRoute.state?.index !== undefined) { activeRoute = activeRoute.state.routes[activeRoute.state.index]; } return activeRoute.name; }); // 所有需要屏蔽滑动唤起抽屉的页面名放这个数组里 const blockSwipeList = ['QRCode']; const enableSwipe = !blockSwipeList.includes(currentRouteName); return ( <Drawer.Navigator screenOptions={{ headerShown: false, swipeEnabled: enableSwipe, // 要完全屏蔽所有手势触发抽屉就加下面这行 // gestureEnabled: enableSwipe }} drawerContent={(props) => <CustomDrawerContent {...props} />} > <Drawer.Screen name="SignedInStack" component={SignedInStack} /> </Drawer.Navigator> ); };
后续新增需要屏蔽手势的页面,直接往blockSwipeList里加页面name就行,不用改单个页面逻辑。
方案2:单页面独立控制
如果屏蔽逻辑和页面自身业务绑定(比如只有页面进入特定编辑状态才需要禁手势),可以直接在对应Stack页面内用生命周期方法控制抽屉锁状态。
比如要在QRCode页面屏蔽手势,直接修改对应页面组件:
import { useFocusEffect, useNavigation } from '@react-navigation/native'; import { useCallback } from 'react'; import { DrawerActions } from '@react-navigation/native'; // QRCode路由对应的Main组件 const Main = () => { const navigation = useNavigation(); useFocusEffect( useCallback(() => { // 页面聚焦时锁死抽屉,禁止滑动唤起 navigation.dispatch(DrawerActions.lockDrawer()); return () => { // 页面销毁/切走时解锁,恢复其他页面的正常滑动 navigation.dispatch(DrawerActions.unlockDrawer()); }; }, [navigation]) ); return ( // 原有页面业务代码 ) }
补充说明
- 如果你用的是v5及更早版本的React Navigation Drawer,没有
swipeEnabled属性,换成drawerLockMode即可,禁用时值传'locked-closed',正常状态传'unlocked'。 - 两种方案选一种用就行,不要同时加避免逻辑冲突。
内容的提问来源于stack exchange,提问作者Tchiteu Abloh
相关产品推荐
相关产品推荐

