簡體   English   中英

如何在 React Navigation 5 中將自定義道具傳遞給抽屜屏幕?

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

這是我的抽屜導航配置:

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

在我的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>
  );
}

我想在DrawerItem組件內的DrawerContent組件中添加一個icon道具。 我試過這樣做:

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

在我的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)}
    />
))}

但是route.icon屬性是undefined 對此有任何想法嗎?

使用Screen 上的 options 道具修復了它。

在我的抽屜導航器中:

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

並在自定義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