首页 > 解决方案 > 有没有办法让 `react-navigation` 的 `indicator` 适合标签?

问题描述

我想适合indicator导航栏的选项卡。但它只适合第一个标签。对于所有其他选项卡,右侧的指示器会滑动一点。我在导航部分使用margins了左右。style下图显示了该场景。

这是第一个标签

这是第二个标签

这是导航组件的代码

const Navigation = createMaterialTopTabNavigator(
    {
        S: Screen1,
        S2: Screen2,
        S3: Screen3,
    },
    {
        swipeEnabled: false,
        tabBarOptions: {
            activeTintColor: "white",
            inactiveTintColor: "blue",
            upperCaseLabel: false,
            scrollEnabled: false,
            inactiveBackgroundColor: "white",
            indicatorStyle: {
                height: null,
                top: 0,
                backgroundColor: 'red',
                width:110,
            },
            style: {
                marginLeft: 15,
                marginRight:15,
                borderWidth: 1,
                height: 30,
                borderColor: "blue",
                backgroundColor: "white",
            },
            tabStyle: {
                borderWidth:1,
                borderColor:"blue",
                justifyContent: "center"
            },
            labelStyle: {
                marginTop: -4
            }
        }
    }
);

export default createAppContainer(Navigation);

我怎样才能解决这个问题 ?

标签: react-nativereact-navigation

解决方案


问题是你的marginLeftmarginRight通过你的整个tabBar传播。

您可以通过引入以下内容来解决此问题:

import { Dimensions } from 'react-native';
const width = Dimensions.get('window').width;
const tabBarWidth = width - 30;  // Subtract margins from your screen width. In your case 2*15= 30 

并更新您的 tabBarOptions:

tabBarOptions: {
            activeTintColor: "white",
            inactiveTintColor: "blue",
            upperCaseLabel: false,
            scrollEnabled: false,
            inactiveBackgroundColor: "white",
            indicatorStyle: {
                height: null,
                top: 0,
                backgroundColor: 'red',
                //width:110,  remove width here
            },
            style: {
                marginTop: 60, // quick hack for iphone X 
                marginLeft: 15,
                marginRight:15,
                borderWidth: 1,
                height: 30,
                borderColor: "blue",
                backgroundColor: "white",
            },
            tabStyle: {
                borderWidth:1,
                borderColor:"blue",
                justifyContent: "center",
                width: tabBarWidth/4, // divided by amount of screens you have 
            },
            labelStyle: {
                marginTop: -4
            }
        } 

如您所见,结果也适用于例如 4 个选项卡:

带有 4 个选项卡的示例


推荐阅读