React Native TabNavigator点击时图标颜色修改问题求助
Hey there! I see you're trying to get your TabNavigator icons to change color when tapped, but it's not working yet. Let's fix that together.
The Issue with Your Current Setup
You've already set activeTintColor and inactiveTintColor in tabBarOptions—that's a great start! But these settings only automatically apply to text labels by default. For icons, you need to explicitly tie their color to the tab's active state.
Solution 1: Use Vector Icons (Recommended)
Vector icons (like those from react-native-vector-icons) are perfect for this since they easily support tinting. Here's how to update your code:
First, make sure you have react-native-vector-icons installed (if you haven't already). Then adjust your TabNavigator configuration to add custom tabBarIcon for each screen:
import Ionicons from 'react-native-vector-icons/Ionicons'; // Import your preferred icon set const Tabs = TabNavigator({ About: { screen: About, navigationOptions: { tabBarIcon: ({ focused }) => ( <Ionicons name="information-circle" size={25} color={focused ? 'green' : 'grey'} // Match your active/inactive colors /> ) } }, Search: { screen: Search, navigationOptions: { tabBarIcon: ({ focused }) => ( <Ionicons name="search" size={25} color={focused ? 'green' : 'grey'} /> ) } }, Trois: { screen: Trois, navigationOptions: { tabBarIcon: ({ focused }) => ( <Ionicons name="three-circle" size={25} color={focused ? 'green' : 'grey'} /> ) } }, Quatre: { screen: Quatre, navigationOptions: { tabBarIcon: ({ focused }) => ( <Ionicons name="four-circle" size={25} color={focused ? 'green' : 'grey'} /> ) } } }, { tabBarPosition: 'bottom', animationEnabled: true, tabBarOptions: { activeTintColor: 'green', inactiveTintColor: 'grey', showIcon: true, showLabel: false, style: { backgroundColor: '#ffffff' // Fill in your desired background color } } });
Solution 2: Use Local Image Files
If you're using custom local PNG/SVG icons, you can still tint them using the tintColor style property:
// For each tab's navigationOptions tabBarIcon: ({ focused }) => ( <Image source={require('./path/to/your/icon.png')} // Replace with your icon's file path style={{ width: 25, height: 25, tintColor: focused ? 'green' : 'grey' }} /> )
Key Explanation
The tabBarIcon prop receives a focused boolean that tells you whether the current tab is selected. We use this value to dynamically switch the icon's color between your active (green) and inactive (grey) states.
内容的提问来源于stack exchange,提问作者Begginers

