【问题标题】:How to use different icons for each tab with createBottomTabNavigator?如何使用 createBottomTabNavigator 为每个选项卡使用不同的图标?
【发布时间】:2018-06-14 09:39:23
【问题描述】:

我在我的项目中使用React Native Navigation v2。我正在尝试使用 createBottomTabNavigator 设置两个不同的 IonIcon。

他们的site举了一个这样的例子:

navigationOptions: ({ navigation }) => ({
  tabBarIcon: ({ focused, tintColor }) => {
    const { routeName } = navigation.state;
    let iconName;
    if (routeName === 'Home') {
      iconName = `ios-information-circle${focused ? '' : '-outline'}`;
    } else if (routeName === 'Settings') {
      iconName = `ios-options${focused ? '' : '-outline'}`;
    }

    // You can return any component that you like here! We usually use an
    // icon component from react-native-vector-icons
    return <Ionicons name={iconName} size={25} color={tintColor} />;
  },
}),

但对我来说,这似乎很无聊。我可以在组件本身中定义 IonIcon 吗? 如何使用 React Native Navigation v2 单独定义符号?

【问题讨论】:

    标签: javascript reactjs react-native react-navigation


    【解决方案1】:

    是的,您可以:

    class HomeComponent extends Component {
        static navigationOptions = {
            tabBarIcon: ({ focused, tintColor }) => {
                const iconName = `ios-information-circle${focused ? '' : '-outline'}`;
                return <Ionicons name={iconName} size={25} color={tintColor} />;
            },
        };
    
        // ...
    }
    

    或者:

    const tabs = createBottomTabNavigator({
        Home: {
            screen: HomeComponent,
            path: '/',
            navigationOptions: {
                tabBarIcon: ({ focused, tintColor }) => {
                    const iconName = `ios-information-circle${focused ? '' : '-outline'}`;
                    return <Ionicons name={iconName} size={25} color={tintColor} />;
                },
            },
        },
        // ...
    });
    

    【讨论】:

    • 虽然第二个选项目前有效,但我认为这不是正确的解决方案。如果我想要 20 条路线,并且每条路线都需要一个符号,该怎么办?您将获得多行代码。还有其他更清洁的方法吗?因为第一个选项是最好的选择,但是那个解决方案对我不起作用。
    • 你确定吗?我通过稍微调整this code 尝试了第一个,看起来它可以工作。
    • 选项二对我有用,您发送了选项二的链接。选项一不是您发送的,那对我不起作用。
    • 我试过了,但不幸的是它对我不起作用。谢谢你。
    【解决方案2】:

    虽然投票最多的答案是对的,但也许你不想使用以'-outline'图标版本结尾的解决方案,而想使用不同的图标,所以:


    更改图标(标准矢量图标)聚焦:

    tabBarIcon: ({ tintColor, focused }) => (
        <Ionicons name={focused ? 
                        'ios-home' : 
                        'ios-home-outline'} 
                  size={26} style={{ color: tintColor }} />
    ),
    

    更改图标(使用您想要的任何图像)聚焦:

    tabBarIcon: ({ focused }) => {
            const iconimg = focused  ? 
                  require('../active.png')  : 
                  require('../inactive.png')
            return (
                <Image 
                    source={iconimg}
                    style={styles.tabIcon}
                />
            )
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      相关资源
      最近更新 更多