首页 > 解决方案 > 尝试使用自定义内容创建 React Navigation Drawer

问题描述

我正在尝试使用自定义内容创建一个 React Navigation 抽屉(我想放置个人资料信息,可能不是任何链接)。我这样做有很多麻烦。

这是我的基本堆栈/抽屉:

const Drawer = createDrawerNavigator();

function DrawerNav() {
  return (
    <ScrollView>
      <DrawerItems {...props} />
      <Text>Test Content</Text>
    </ScrollView>
  );
}

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Login" component={Login} options={{
          headerShown: false
        }} />
        <Stack.Screen name="Detail" component={Detail} />
        <Stack.Screen name="Chat" component={Chat} />
        <Stack.Screen name="Leagues" component={Leagues} />
        <Stack.Screen name="Profile" component={Profile} />
        <Stack.Screen name="Home" component={Home} options={{
          headerRight: (navigation) => (
            <TouchableOpacity onPress={(navigation) => navigation.dispatch(DrawerActions.toggleDrawer())}>
              <EvilIcons name="navicon" size={50} color="black" />
            </TouchableOpacity>
          ),
          headerLeft: () => (
            null
          ),
        }} />
        <Stack.Screen name="CommForm" component={CommForm} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

我想要的,实际上就是我想要的,是一个侧边栏,我可以通过按下<TouchableOpacity>上面带有自定义内容的按钮来切换它。

我可以使用 React Native Side Menu 来做到这一点,但是如果我使用 React Navigation,我应该学习如何使用这个库来做到这一点,但是做我想做的事情似乎非常困难。

如何使用 React Navigation 创建包含自定义内容的侧边栏?我主要想使用堆栈导航。

标签: javascriptreactjsreact-nativereact-navigation

解决方案


我会做这样的事情:

function CustomDrawerContent(props) {
  return (
    <DrawerContentScrollView {...props}>
      <DrawerItem label="..." />
      // ...
    </DrawerContentScrollView>
  );
}

function StackNavigator({navigation}) {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        component={Home}
        options={{
          headerRight: () => (
            <Button title="press" onPress={() => navigation.toggleDrawer()} />
          ),
        }}
      />
      // Your other screens... 
    </Stack.Navigator>
  );
}

function DrawerNavigator({navigation, route}) {
  return (
    <Drawer.Navigator
      drawerContent={(props) => <CustomDrawerContent {...props} />}>
      <Drawer.Screen name="Stack" component={StackNavigator} />
    </Drawer.Navigator>
  );
}

const App = () => {
  return (
    <NavigationContainer>
      <DrawerNavigator />
    </NavigationContainer>
  );
};

因此,您可以将抽屉导航设置为主导航器,将堆栈导航设置为抽屉导航的屏幕。这样您就可以切换抽屉,而无需先导航到它。

要创建自定义抽屉内容,您可以将组件传递给drawerContent抽屉导航器。

如果您要使用DrawerContentScrollView和/或DrawerItem像我在此示例中所做的那样,请务必从'@react-navigation/drawer'; .

查看文档以获取更多信息https://reactnavigation.org/docs/drawer-navigator/#providing-a-custom-drawercontent


推荐阅读