简体   繁体   中英

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:

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. I tried doing this:

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

and in my 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 . Any idea on this?

Fixed it using options prop on Screen .

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:

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>
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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