简体   繁体   English

如何在 React Navigation 5 中将自定义道具传递给抽屉屏幕?

[英]How to pass custom props to drawer screens in React Navigation 5?

Here's my Drawer Navigation config:这是我的抽屉导航配置:

  return (
    <NavigationContainer theme={navigationTheme}>
      <Drawer.Navigator
        drawerContent={(props) => (
          <DrawerContent {...props} />
        )}
      >
        <Drawer.Screen name="Home" component={HomeScreen} />
        <Drawer.Screen name="About" component={AboutScreen} />
      </Drawer.Navigator>
    </NavigationContainer>
  );

and in my DrawerContent component:在我的DrawerContent组件中:

export default function DrawerContent({ state, navigation, ...props }) {
  return (
    <DrawerContentScrollView {...props}>
        <Drawer.Section>
          {state.routes.map((route) => (
            <DrawerItem
              key={route.key}
              label={route.name}
              onPress={() => navigation.navigate(route.name)}
            />
          ))}
        </Drawer.Section>
      </View>
    </DrawerContentScrollView>
  );
}

I want to add an icon prop to my DrawerItem component inside the DrawerContent component.我想在DrawerItem组件内的DrawerContent组件中添加一个icon道具。 I tried doing this:我试过这样做:

<Drawer.Screen name="Home" icon="home" component={HomeScreen} />

and in my DrawerContent在我的DrawerContent

{state.routes.map((route) => (
    <DrawerItem
        key={route.key}
        icon={({ color, size }) => (
        <MaterialCommunityIcons name="home" icon={route.icon} color={color} size={size} />
        )}
        label={route.name}
        onPress={() => navigation.navigate(route.name)}
    />
))}

But the route.icon property is undefined .但是route.icon属性是undefined Any idea on this?对此有任何想法吗?

Fixed it using options prop on Screen .使用Screen 上的 options 道具修复了它。

In my Drawer Navigator:在我的抽屉导航器中:

<Drawer.Navigator>
  <Drawer.Screen
    name="Home"
    component={HomeScreen}
    options={{ icon: 'home' }}
  />
</Drawer.Navigator>

and to access it in the custom DrawerContent component:并在自定义DrawerContent组件中访问它:

export default function DrawerContent({ state, navigation, ...props }) {

    const getIcon = (key) => props.descriptors[key].options.icon;

    return (
        <DrawerContentScrollView {...props}>
            <Drawer.Section>
            {state.routes.map((route) => (
                <DrawerItem
                key={route.key}
                label={route.name}
                icon={({ color, size }) => (
                    <MaterialCommunityIcons
                        name={getIcon(route.key)}
                        color={color}
                        size={size}
                    />
                )}
                onPress={() => navigation.navigate(route.name)}
                />
            ))}
            </Drawer.Section>
        </View>
        </DrawerContentScrollView>
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM