[英]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.