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

React Navigation平板端侧边栏控制:仅在A页面显示

实现平板侧边栏仅在指定页面显示

要实现仅在名称为'A'的Dashboard页面显示SideBar,其他页面隐藏的需求,你可以通过监听当前路由状态来控制侧边栏的渲染,具体操作如下:

  1. 导入React Navigation的useNavigationState钩子
  2. 获取当前活跃路由的名称
  3. 根据路由名称条件渲染SideBar组件

修改后的完整代码如下:

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

const RoutesTablet = () => {
  // 获取当前活跃的路由名称
  const currentRouteName = useNavigationState(state => state.routes[state.index].name);

  return (
    <Div row flex={1}>
      <StatusBar backgroundColor={COLOR_PRIMARY} />
      <Drawer.Navigator
        initialRouteName="A"
        screenOptions={{
          headerStyle: {
            backgroundColor: COLOR_PRIMARY,
            // height: heightPercentageToDP(8),
          },
        }}
      >
        <Drawer.Screen
          name="A"
          component={Dashboard}
          options={{
            headerTitle: "Bob",
            headerRight: () => (
              <Image
                source={require("..........")}
                w={widthPercentageToDP(25)}
                h={heightPercentageToDP(4)}
                resizeMode="contain"
              />
            ),
          }}
        />
        <Drawer.Screen name="B" component={Sales} />
      </Drawer.Navigator>
      {/* 仅当当前路由为'A'时渲染侧边栏 */}
      {currentRouteName === 'A' && <SideBar />}
    </Div>
  );
};

关键说明:

  • useNavigationState钩子可获取导航器的完整状态,通过state.routes[state.index].name能直接拿到当前显示页面的路由名称
  • 使用逻辑与运算符&&实现条件渲染:只有当currentRouteName等于'A'时,SideBar才会被渲染,切换到其他页面时会自动隐藏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:30:41