React Native中@react-navigation/material-bottom-tabs无法自定义完整标签栏
完全自定义标签栏的实现如下:
你已经在Tab.Navigator上通过tabBar属性传入了自定义组件<MyTabBar />,补充MyTabBar组件的实现代码:
import * as React from 'react'; import { View, TouchableOpacity, Text, StyleSheet } from 'react-native'; function MyTabBar({ state, descriptors, navigation }) { return ( <View style={styles.tabBarContainer}> {state.routes.map((route, index) => { const { options } = descriptors[route.key]; const label = options.tabBarLabel !== undefined ? options.tabBarLabel : options.title !== undefined ? options.title : route.name; const isFocused = state.index === index; const onPress = () => { const event = navigation.emit({ type: 'tabPress', target: route.key, canPreventDefault: true, }); if (!isFocused && !event.defaultPrevented) { navigation.navigate(route.name, route.params); } }; const onLongPress = () => { navigation.emit({ type: 'tabLongPress', target: route.key, }); }; return ( <TouchableOpacity accessibilityRole="button" accessibilityState={isFocused ? { selected: true } : {}} accessibilityLabel={options.tabBarAccessibilityLabel} testID={options.tabBarTestID} onPress={onPress} onLongPress={onLongPress} style={styles.tabItem} key={route.key} > {/* 此处可自定义插入图标、修改文字样式等逻辑 */} <Text style={{ color: isFocused ? '#673ab7' : '#222' }}> {label} </Text> </TouchableOpacity> ); })} </View> ); } const styles = StyleSheet.create({ tabBarContainer: { flexDirection: 'row', position: 'absolute', bottom: 20, left: 20, right: 20, elevation: 2, backgroundColor: '#fff', borderRadius: 15, height: 60, paddingHorizontal: 10, }, tabItem: { flex: 1, justifyContent: 'center', alignItems: 'center', } })
如果仅需要修改默认标签栏的样式,不需要完全重写组件,直接在Tab.Navigator上配置screenOptions即可:
<Tab.Navigator screenOptions={{ tabBarActiveTintColor: '#e91e63', tabBarInactiveTintColor: '#888', tabBarStyle: { backgroundColor: '#f5f5f5', paddingBottom: 5, height: 65 }, tabBarLabelStyle: { fontSize: 12 } }} > <Tab.Screen name="Home" component={HomeScreen} /> <Tab.Screen name="Settings" component={SettingsScreen} /> </Tab.Navigator>
注意:@react-navigation/material-bottom-tabs 是基于Material Design规范封装的实现,样式约束较多,如果需要更高的自定义自由度,可以替换为@react-navigation/bottom-tabs库实现底部标签栏。
内容的提问来源于stack exchange,提问作者enal
相关产品推荐
相关产品推荐

