9-3 顶部标签导航器

186 阅读1分钟

在本节中,我们将学习如何使用顶部标签导航器。

一、安装依赖

顶部标签导航器需要以下依赖:

yarn add @react-navigation/material-top-tabs react-native-tab-view

二、创建顶部标签导航器

navigator/HomeTabs.tsx 中创建顶部标签导航器:

import React from 'react';
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';

// 定义导航器页面参数
export type HomeTabParamList = {
  Home: undefined;
  Category: undefined;
  Search: undefined;
  Profile: undefined;
};

// 创建导航器
const Tab = createMaterialTopTabNavigator<HomeTabParamList>();

const HomeTabs = () => (
  <Tab.Navigator
    tabBarOptions={{
      scrollEnabled: true,
      tabStyle: {
        padding: 0,
        width: 80,
      },
      indicatorStyle: {
        height: 4,
        width: 20,
        marginLeft: 30,
        borderRadius: 2,
        backgroundColor: '#fff',
      },
      activeTintColor: '#fff',
      inactiveTintColor: '#fff',
      labelStyle: {
        fontSize: 14,
        fontWeight: 'bold',
      },
      style: {
        backgroundColor: '#4CAF50', // 渐变色背景
        marginTop: 0,
      },
    }}
  >
    <Tab.Screen name="Home" component={HomeScreen} options={{ tabBarLabel: '推荐' }} />
    <Tab.Screen name="Category" component={CategoryScreen} options={{ tabBarLabel: '类别' }} />
    <Tab.Screen name="Search" component={SearchScreen} options={{ tabBarLabel: '搜索' }} />
    <Tab.Screen name="Profile" component={ProfileScreen} options={{ tabBarLabel: '我的' }} />
  </Tab.Navigator>
);

export default HomeTabs;

三、集成顶部标签导航器

navigator/BottomTabs.tsx 中集成顶部标签导航器:

import HomeTabs from './HomeTabs';

const BottomTabNavigator = createBottomTabNavigator();

<BottomTabNavigator>
  <BottomTab.Screen
    name="HomeTabs"
    component={HomeTabs}
    options={{
      tabBarLabel: '首页',
      tabBarIcon: ({ color, size }) => (
        <Icon name="icon-shouye" color={color} size={size} />
      ),
    }}
  />
  <BottomTab.Screen
    name="Discover"
    component={DiscoverScreen}
    options={{
      tabBarLabel: '发现',
      tabBarIcon: ({ color, size }) => (
        <Icon name="icon-faxian" color={color} size={size} />
      ),
    }}
  />
  <BottomTab.Screen
    name="Cart"
    component={CartScreen}
    options={{
      tabBarLabel: '购物车',
      tabBarIcon: ({ color, size }) => (
        <Icon name="icon-shoucang" color={color} size={size} />
      ),
    }}
  />
  <BottomTab.Screen
    name="Profile"
    component={ProfileScreen}
    options={{
      tabBarLabel: '我的',
      tabBarIcon: ({ color, size }) => (
        <Icon name="icon-user" color={color} size={size} />
      ),
    }}
  />
</BottomTabNavigator>;

四、设置状态栏

src/index.tsx 中设置状态栏,使 Android 端从最顶部开始渲染:

import { StatusBar } from 'react-native';

<StatusBar
  backgroundColor="transparent"
  barStyle="dark-content"
  translucent
/>;

五、总结

在本节中,我们学习了如何安装和使用顶部标签导航器,并对其进行了美化。通过配置 tabBarOptions,可以实现渐变背景、滚动支持、标签样式和指示器样式等效果。下一节,我们将学习如何使用轮播图。