React抽屉式导航工具条

mefy6pfw  于 2023-02-09  发布在  React
关注(0)|答案(1)|浏览(162)

在这我试图使一个侧边栏的平板电脑用户界面,我想尝试,以便如果
抽屉。屏幕名称= 'A'
侧边栏将显示,但如果更改屏幕,侧边栏不会显示在其屏幕上
这是路线的代码

const RoutesTablet = () => {

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>
      <SideBar />
    </Div>
  );
};
6jygbczu

6jygbczu1#

一个可能的解决方案是跟踪NavigationContainerlink to doc)的状态并更新当前屏幕名称,我们只在当前屏幕名称为'A'时才呈现SideBar

演示

源码

import * as React from 'react';
import {Text, View} from 'react-native';
import {createDrawerNavigator} from '@react-navigation/drawer';
import {NavigationContainer} from '@react-navigation/native';

const A = () => <View />;
const B = () => <View />;

const SideBar = () => (
  <View
    style={{
      position: 'absolute',
      justifyContent: 'space-around',
      right: 0,
      top: '25%',
      width: '10%',
      height: '50%',
      backgroundColor: 'lightblue',
    }}>
    {'sidebar'.split('').map(text => (
      <View key={text} style={{alignItems: 'center'}}>
        <Text>{text}</Text>
      </View>
    ))}
  </View>
);

const Drawer = createDrawerNavigator();

export default function App() {
  const ref = React.useRef(null);
  const [curScreen, setCurScreen] = React.useState('A');

  React.useEffect(() => {
    // Use this to constantly listen to the current state of
    // NavigationContainer and update curScreen
    const unsubscribe = ref.current.addListener('state', e => {
      const lastHist = e.data.state.history.slice(-1)[0];
      if (lastHist.type === 'drawer') {
        setCurScreen('drawer');
      } else {
        setCurScreen(ref.current.getCurrentRoute().name);
      }
    });
    return unsubscribe;
  });

  return (
    <NavigationContainer ref={ref}>
      <Drawer.Navigator initialRouteName="A">
        <Drawer.Screen name="A" component={A} />
        <Drawer.Screen name="B" component={B} />
      </Drawer.Navigator>
      {curScreen === 'A' && <SideBar />}
    </NavigationContainer>
  );
}

相关问题