首页 > 解决方案 > React Naitve Navigation:如何从抽屉中显示模式?

问题描述

有没有办法在 React Native 中从抽屉中显示模式?有一个类似的问题,我按照答案更改了我的代码。

我现在的代码是这样的。

MyRootStackNavigator.tsx

const Stack = createStackNavigator<RootStackParamList>();

const MyRootStackNavigator = () => {

  return (
    <Stack.Navigator mode="modal">
      <Stack.Screen
        name="Main"
        component={MyDrawerNavigator}
        options={{ headerShown: false }}
      />
      <Stack.Screen 
        name="MyModal"
        component={MyModal}
      />
    </Stack.Navigator>
  );
};

MyDrawerNavigation.tsx

const Drawer = createDrawerNavigator();

const MyDrawerNavigator = () => {

  return (
    <Drawer.Navigator>
      <Drawer.Screen
        name="Home"
        component={MyStackNavigator}
      />
      <Drawer.Screen
        name="About this app"
        component={About}
      />
    </Drawer.Navigator>
  );
}

但是对于此代码,显示模式的部分不会出现在抽屉上。只有HomeAbout this app部分出现在抽屉上。如何设置部分以在抽屉上显示模式?

标签: reactjsreact-nativereact-native-navigation

解决方案


您可以使用内部有模态的 CustomDrawerContent 并使用按钮打开模态

function CustomDrawerContent(props) {
  const [modalVisible, setModalVisible] = useState(false);
  return (
    <DrawerContentScrollView {...props}>
      <Modal
        style={{ flxe: 1, backgroundColor: 'red' }}
        visible={modalVisible}
        onRequestClose={() => setModalVisible(false)}>
        <Text>Modal Content Here</Text>
        <Button title="Close" onPress={() => setModalVisible(false)} />
      </Modal>
      <DrawerItemList {...props} />
      <DrawerItem
        label="Open Modal"
        onPress={() => {
          setModalVisible(true);
        }}
      />
    </DrawerContentScrollView>
  );
}

DrawerNavigator 应该像这样设置

<Drawer.Navigator
  drawerContent={(props) => <CustomDrawerContent {...props} />}>

您可以在此处参考文档 https://reactnavigation.org/docs/drawer-navigator/#providing-a-custom-drawercontent

如果您想继续使用您在问题中输入的代码,您可以像下面那样导航到关于屏幕(而不是在内容中包含模式)

  <DrawerItem
    label="Open Screen"
    onPress={() => {
      props.navigation.navigate('About')
    }}
  />

推荐阅读