React Navigation平板端侧边栏控制:仅在A页面显示
实现平板侧边栏仅在指定页面显示
要实现仅在名称为'A'的Dashboard页面显示SideBar,其他页面隐藏的需求,你可以通过监听当前路由状态来控制侧边栏的渲染,具体操作如下:
- 导入React Navigation的
useNavigationState钩子 - 获取当前活跃路由的名称
- 根据路由名称条件渲染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
相关产品推荐
相关产品推荐

