React Navigation修改底部Tab图标 解决图标显示问号报错
问题原因
React Navigation底部Tab显示问号错误占位,是因为未给Tab项配置tabBarIcon属性,导航无法加载对应图标资源导致。
修复方案
你只需要给每个Tab项配置对应的图标渲染函数即可,以下是基于你现有代码修改的完整可运行版本,首页已经替换为你需要的Entypo home图标,个人页同步配置了对应图标避免出现占位错误:
import * as React from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { View, Text } from 'react-native'; // 引入需要的图标组件 import { Entypo } from '@expo/vector-icons'; const HomeScreen = () => { return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Text>Home Screen</Text> </View> ); }; const ProfileScreen = () => { return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Text>This is profile</Text> </View> ); }; const Tab = createBottomTabNavigator(); const App = () => { return ( <NavigationContainer> <Tab.Navigator screenOptions={({ route }) => ({ tabBarIcon: ({ focused, color, size }) => { // 根据当前路由名返回对应图标 if (route.name === 'Home') { // 首页使用指定的Entypo home图标 return <Entypo name="home" size={size} color={color} />; } else if (route.name === 'Profile') { // 个人页使用Entypo的user图标,可按需替换为其他图标 return <Entypo name="user" size={size} color={color} />; } }, // Tab激活/未激活状态颜色,可按需自定义修改 tabBarActiveTintColor: 'tomato', tabBarInactiveTintColor: 'gray', })} > <Tab.Screen name="Home" component={HomeScreen} /> <Tab.Screen name="Profile" component={ProfileScreen} /> </Tab.Navigator> </NavigationContainer> ); }; export default App;
补充说明
- 标准Expo项目默认预装
@expo/vector-icons依赖,直接引入即可使用;如果是裸React Native项目,需要先执行npm install @expo/vector-icons安装依赖后再运行。 tabBarIcon回调会自动接收当前Tab的标准尺寸、主题色参数,以及聚焦状态标识,你可以根据focused值自定义不同状态下的图标样式,比如聚焦时显示实心图标、未聚焦时显示线性图标。
内容的提问来源于stack exchange,提问作者정혜주
相关产品推荐
相关产品推荐

