React Native中为DrawerNavigation菜单项添加退出登录图标方法
嘿,我来帮你搞定这个事儿!其实步骤很简单,咱们一步步来:
首先,你得先选一个图标库来用,React生态里最常用的就是@react-native-vector-icons下面的系列,比如Ionicons、MaterialIcons这些。先把依赖装上:
# 用npm安装 npm install @react-native-vector-icons/ionicons # 或者用yarn yarn add @react-native-vector-icons/ionicons
接下来就是修改你现有的抽屉导航配置啦。你之前的写法是直接把组件传给路由,现在要改成每个路由是一个包含screen和options的对象,在options里配置drawerIcon属性就行:
import { createDrawerNavigator } from '@react-navigation/drawer'; import Ionicons from '@react-native-vector-icons/Ionicons'; // 先导入图标组件 const Drawer = createDrawerNavigator(); const AppDrawerNavigator = () => { return ( <Drawer.Navigator initialRouteName="Rendez Vous"> <Drawer.Screen name="Rendez Vous" component={RendezVous} options={{ drawerIcon: ({ focused, color, size }) => ( <Ionicons name="calendar" size={size} color={color} /> ) }} /> <Drawer.Screen name="Parcours de soin" component={ParcoursDeSoin} options={{ drawerIcon: ({ focused, color, size }) => ( <Ionicons name="medical" size={size} color={color} /> ) }} /> <Drawer.Screen name="Ordonnances" component={Ordonnances} options={{ drawerIcon: ({ focused, color, size }) => ( <Ionicons name="file-tray-full" size={size} color={color} /> ) }} /> <Drawer.Screen name="Analyses" component={Analyses} options={{ drawerIcon: ({ focused, color, size }) => ( <Ionicons name="clipboard" size={size} color={color} /> ) }} /> <Drawer.Screen name="Profil" component={Profil} options={{ drawerIcon: ({ focused, color, size }) => ( <Ionicons name="person" size={size} color={color} /> ) }} /> <Drawer.Screen name="A Propos" component={APropos} options={{ drawerIcon: ({ focused, color, size }) => ( <Ionicons name="information-circle" size={size} color={color} /> ) }} /> <Drawer.Screen name="Logout " component={Login} options={{ drawerIcon: ({ focused, color, size }) => ( <Ionicons name="log-out" size={size} color={color} /> ) }} /> </Drawer.Navigator> ); };
小细节说明:
drawerIcon是个函数,会给你三个参数:focused(当前项有没有被选中)、color(系统默认的颜色,选中和未选中会自动变化)、size(图标大小,你可以自己调整或者用系统默认值)。- 图标名称可以随便换,比如你想用MaterialIcons的话,就导入
MaterialIcons,然后把name改成对应的,比如"account-circle"这类的。 - 要是你用的是旧版React Navigation(比如v4及更早版本),写法稍微有点不一样,得在
createDrawerNavigator的配置里给每个路由加navigationOptions:
// 旧版v4写法示例 const AppDrawerNavigator = createDrawerNavigator( { 'Rendez Vous': { screen: RendezVous, navigationOptions: { drawerIcon: ({ tintColor }) => ( <Ionicons name="calendar" size={20} color={tintColor} /> ) } }, // 其他路由照着这个格式来就行... }, { contentOptions: { activeTintColor: '#e91e63', // 选中项的颜色,自己改成喜欢的 inactiveTintColor: '#333' // 未选中项的颜色 } } );
这样配置完,你的抽屉导航菜单项就都有图标啦,而且选中的时候图标颜色还会自动切换,完美~
内容的提问来源于stack exchange,提问作者xcode
相关产品推荐
相关产品推荐

