如何解决如何使用React Navigation 5创建自定义标签栏?
所以,这是我的标签栏:
我试图在按下按钮时仅在屏幕之间使用通用导航,但这在我的情况下不起作用。我在Google中看到的所有方法也已弃用。是否可以在React Navigation 5中创建自定义选项卡?
解决方法
您应该实现您的自定义标签栏,正如您在屏幕截图中所显示的那样,我创建了一个 Live Snack
import * as React from 'react';
import { View,Text,TouchableOpacity } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { MaterialCommunityIcons } from '@expo/vector-icons';
function HomeScreen() {
return (
<View
style={{
flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: '#fff',}}>
<Text>Home!</Text>
</View>
);
}
function SettingsScreen() {
return (
<View style={{ flex: 1,alignItems: 'center' }}>
<Text>Settings!</Text>
</View>
);
}
function MyTabBar({ state,descriptors,navigation }) {
return (
<View
style={{
position: 'absolute',bottom: 0,left: 0,right: 0,flexDirection: 'row',backgroundColor: '#ccc',height: 60,borderTopRightRadius: 20,borderTopLeftRadius: 20,justifyContent: 'space-between',}}>
{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,});
if (!isFocused && !event.defaultPrevented) {
navigation.navigate(route.name);
}
};
const onLongPress = () => {
navigation.emit({
type: 'tabLongPress',});
};
return (
<TouchableOpacity
accessibilityRole="button"
accessibilityStates={isFocused ? ['selected'] : []}
accessibilityLabel={options.tabBarAccessibilityLabel}
testID={options.tabBarTestID}
onPress={onPress}
onLongPress={onLongPress}
style={{ flex: 1,justifyContent: 'space-between' }}>
{route.name === 'Home' ? (
<MaterialCommunityIcons
style={{ alignSelf: 'center' }}
name="home"
size={22}
color={isFocused ? '#673ab7' : '#222'}
/>
) : (
<MaterialCommunityIcons
style={{ alignSelf: 'center' }}
name="settings"
color={isFocused ? '#673ab7' : '#222'}
size={22}
/>
)}
<View
style={{
width: 8,height: 3,backgroundColor: isFocused ? '#00f' : '#777',alignSelf: 'center',}}
/>
</TouchableOpacity>
);
})}
</View>
);
}
const Tab = createBottomTabNavigator();
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator
tabBarOptions={{
showIcon: true,showLabel: false,activeTintColor: 'red',}}
tabBar={(props) => <MyTabBar {...props} />}>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="Settings" component={SettingsScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。