React Native自定义导航抽屉时如何为抽屉项添加按钮与图标?
React Native 抽屉自定义图标按钮实现方案
方案1:使用DrawerItem自带icon属性(改动最小,保留原生抽屉样式)
DrawerItem组件原生支持icon参数,可直接传入图标组件,无需修改原有结构:
- 先安装适配的图标库,expo项目推荐用
@expo/vector-icons,原生RN项目推荐用react-native-vector-icons,完成对应配置后导入所需图标。 - 调整
CustomDrawerContent代码如下:
import { DrawerContentScrollView, DrawerItemList, DrawerItem } from '@react-navigation/drawer'; import { Linking } from 'react-native'; // 导入图标,可替换为你使用的图标库 import FontAwesome from '@expo/vector-icons/FontAwesome'; function CustomDrawerContent(props: DrawerContentComponentProps) { return ( <DrawerContentScrollView {...props} > <DrawerItemList {...props} /> <DrawerItem label="Facebook" onPress={() => Linking.openURL('https://www.facebook.com/mysite/')} inactiveTintColor="black" // 新增icon属性,返回图标组件 icon={({focused, size, color}) => <FontAwesome name="facebook-square" size={size} color={color} />} /> <DrawerItem label="Instagram Page" onPress={() => Linking.openURL('https://www.instagram.com/mysite/')} inactiveTintColor="black" icon={({focused, size, color}) => <FontAwesome name="instagram" size={size} color={color} />} /> </DrawerContentScrollView> ) }
icon参数的回调会自动传入当前选中状态、推荐大小、适配颜色,你也可以自定义固定的尺寸和颜色值。
方案2:完全自定义按钮组件(自由度最高,可自定义任意样式)
如果你不想要DrawerItem的默认样式,想要做成纯图标按钮、横向排列的按钮组等自定义样式,可以直接替换成任意可点击组件:
import { DrawerContentScrollView, DrawerItemList } from '@react-navigation/drawer'; import { Linking, View, TouchableOpacity, StyleSheet } from 'react-native'; import FontAwesome from '@expo/vector-icons/FontAwesome'; function CustomDrawerContent(props: DrawerContentComponentProps) { return ( <DrawerContentScrollView {...props} > <DrawerItemList {...props} /> {/* 自定义图标按钮区域 */} <View style={styles.iconRow}> <TouchableOpacity onPress={() => Linking.openURL('https://www.facebook.com/mysite/')} style={styles.iconBtn} > <FontAwesome name="facebook-square" size={24} color="#1877f2" /> </TouchableOpacity> <TouchableOpacity onPress={() => Linking.openURL('https://www.instagram.com/mysite/')} style={styles.iconBtn} > <FontAwesome name="instagram" size={24} color="#E4405F" /> </TouchableOpacity> </View> </DrawerContentScrollView> ) } const styles = StyleSheet.create({ iconRow: { flexDirection: 'row', paddingHorizontal: 20, paddingVertical: 15, gap: 20 }, iconBtn: { padding: 8 } })
注意事项
- 图标库安装后需按照官方文档完成对应平台的配置,原生RN项目使用
react-native-vector-icons需要执行pod安装和安卓资源配置 - 跳转外部链接前可先调用
Linking.canOpenURL判断是否支持跳转,避免出现异常 - 安卓平台需要在
AndroidManifest.xml中配置对应域名的queries规则,iOS需要在Info.plist中配置LSApplicationQueriesSchemes白名单,保证跳转正常
内容的提问来源于stack exchange,提问作者nasif92
相关产品推荐
相关产品推荐

