首页 > 解决方案 > 如何为 React Navigation TabBar 创建渐变边框颜色

问题描述

我想在我的 TabBar 上放置一个细渐变边框。我尝试使用 BorderTopColor 样式简单地实现它,但 React Native 默认不支持渐变。所以我安装了www.npmjs.com/package/react-native-linear-gradient。但是,我不知道将渐变容器放置在我的 TabBar 和 Screens 之间。

这是我到目前为止所拥有的:

const Tab = createBottomTabNavigator();

const App: () => Node = () => {
  const customTabBarStyle = {
    activeTintColor: '#ffffff',
    inactiveTintColor: '#b9b9b9',
    showLabel: false,
    style: {
      backgroundColor: '#1e1e1e',
      height: 200
    }
  };

  return (
    <NavigationContainer>
      <LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 0}} colors={['red', 'yellow']} style={{height: 2}} />
      <Tab.Navigator
        tabBarOptions = {customTabBarStyle}
        screenOptions={{ tabBarStyle: { backgroundColor: '#1e1e1e', borderTopWidth: 0, elevation: 0}, headerStyle: { backgroundColor: '#1e1e1e'}, headerTitleStyle: {color: 'white'}}}>
        <Tab.Screen
          name="PrimaryMarket"
          component={PrimaryMarketScreen}
          options={{
            tabBarIcon: ({color}) => (
              <Icon name="shopping-cart" size={40} color={color} />
            ),
          }}
        />
      </Tab.Navigator>
    </NavigationContainer>
  );
};

这是我想要的:

在此处输入图像描述

标签: react-nativereact-navigationgradient

解决方案


我有同样的问题,所以我查看了 react-navigation v6 的源代码来解决问题。在源代码中,我发现了这个tabBarBackground

返回一个 React 元素用作标签栏背景的函数。您可以渲染图像、渐变、模糊视图等。

你可以像下面这样在tabBarBackground里面使用:screenOptions

const Tab = createBottomTabNavigator();

const App: () => Node = () => {
  const customTabBarStyle = {
    activeTintColor: "#ffffff",
    inactiveTintColor: "#b9b9b9",
    showLabel: false,
    style: {
      backgroundColor: "#1e1e1e",
      height: 200,
    },
  };

  return (
    <NavigationContainer>
      <Tab.Navigator
        tabBarOptions={customTabBarStyle}
        screenOptions={{
          tabBarStyle: {
            borderTopWidth: 0,
            elevation: 0,
          },
          headerStyle: { backgroundColor: "#1e1e1e" },
          headerTitleStyle: { color: "white" },
          tabBarBackground: () => (
            <View style={{ flex: 1 }}>
              <LinearGradient
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 0 }}
                colors={["red", "yellow"]}
                style={{ height: 2 }}
              />
            </View>
          ),
        }}
      >
        <Tab.Screen
          name="PrimaryMarket"
          component={PrimaryMarketScreen}
          options={{
            tabBarIcon: ({ color }) => (
              <Icon name="shopping-cart" size={40} color={color} />
            ),
          }}
        />
      </Tab.Navigator>
    </NavigationContainer>
  );
};

不同的代码,但我使用了相同的技术:

展示


推荐阅读