3.4.2 自定义顶部标签栏样式
图3-5 的效果和图3-3 的效果差距挺大的,这时候就需要自定义标签栏的样式,参考官网文档:https://reactnavigation.org/docs/en/material-top-tab-navigator.html
添加 createMaterialTopTabNavigator 的第二个参数,自定义标签栏样式。修改 App.js
代码,参考代码片段 3-4-2。
import CustomTabBar from './src/component/CustomTabBar';
const CategoryTab = createMaterialTopTabNavigator({
CategoryPage: {
screen: CategoryPage,
navigationOptions: {
tabBarLabel: '品类'
}
},
BrandPage: {
screen: BrandPage,
navigationOptions: {
tabBarLabel: '品牌'
}
}
}, {
swipeEnabled: true,// 允许左右滑动
animationEnabled: true,//切换页面时显示动画
backBehavior: 'none',
tabBarOptions: {
// tabbar上label的style
labelStyle: {
//marginTop:0
},
// tabbar的style
style: {
height: 64,
marginHorizontal: theme.screenWidth / 6,
paddingTop: 20,
backgroundColor: '#fff'
},
tabStyle: {
width: theme.screenWidth * 1 / 3
},
// label和icon的背景色 活跃状态下
activeBackgroundColor: '#fff',
// label和icon的前景色 活跃状态下(选中)
activeTintColor: theme.primaryColor,
// label和icon的背景色 不活跃状态下
inactiveBackgroundColor: '#fff',
// label和icon的前景色 不活跃状态下(未选中)
inactiveTintColor: theme.lightBlack,
showIcon: false, // 是否显示 Icon
// 是否显示label,默认为true
showLabel: true,
// 不透明度为按选项卡(适用于iOS和Android < 5.0)
pressOpacity: 0.3,
indicatorStyle: { // Tabbar下划线样式
height: 2,
width: theme.screenWidth / 9,
backgroundColor: theme.primaryColor,
left: theme.screenWidth / 9
}
},
//自定义 TabBar
tabBarComponent: (props) => (
<CustomTabBar {...props}/>
)
});
代码片段 3-4-2
代码虽然增加了很多,其实就是添加了 createMaterialTopTabNavigator 的第二个参数。
- swipeEnabled 是否允许手势左右滑动切换页面,默认允许;
- animationEnabled 点击选项卡切换的时候,是否有动画;
- backBehavior 可以设置 'none' 和 'initialRoute'(默认值) ,表示当点击返回按钮时是否会导致选项卡切换到初始选项卡,'none' 表示不返回到初始选项卡;
- tabBarOptions 定义了顶部标签栏的的样式,具体参考代码注释;
- tabBarComponent 用来自定义顶部选项卡组件替换默认的,参考图3-3,顶部标签栏右边有一个搜索按钮,如果只修改选项卡的样式已经无法实现需求,必须自定义顶部选项卡组件替换掉默认的。通过
{...props}
把默认选项卡的所有属性传递给了CustomTabBar
,这也是必须要做的。
参考代码片段 3-4-3 通过代码实现 CustomTabBar ,代码文件路径:/src/component/CustomTabBar.js
import React, {Component} from 'react';
import {
View,
TouchableOpacity
} from 'react-native';
import {MaterialTopTabBar} from 'react-navigation-tabs'
import Ionicons from 'react-native-vector-icons/Ionicons';
class CustomTabBar extends Component {
render() {
return (
<View style={{position: 'relative', backgroundColor: '#fff'}}>
<MaterialTopTabBar {...this.props}/>
<TouchableOpacity style={{position: 'absolute', right: 12, bottom: 10}}>
<Ionicons name={'ios-search-outline'}
size={22}
color={'#666666'}/>
</TouchableOpacity>
</View>
);
}
}
export default CustomTabBar;
代码片段 3-4-3
CustomTabBar 中一定要导入 MaterialTopTabBar ,组件的写法也是固定的:<MaterialTopTabBar {...this.props}/>
。 这个组件本身就是用来定义选项卡的,代码片段3-4-2 中的 tabBarOptions 里定义的样式在这个组件中是生效的。
搜索按钮的位置通过绝对布局控制,距离父组件右面和父组件底部分别为 12 和 10个单位;图片使用 Ionicons 实现。
运行结果如图3-6 所示。
图3-6 运行结果
查看代码
如果你已经从 GitHub 上克隆了这个程序的 Git 仓库,那么可以执行 git checkout 3c 签出程序的这个版本。