React Native 底部导航设置以及如何隐藏Tab navigation自带的标题栏
安装依赖
由于直接跳过了React Navigation所以需要安装这个导航栈依赖
npm install @react-navigation/native-stack
npm install @react-navigation/bottom-tabs
# 或者
yarn add @react-navigation/native-stack
yarn add @react-navigation/bottom-tabs
其它依赖接之前的文章
思来想去还是放前面吧,因为底部导航是需要图标的,所以我们可以引入一个图标库
npm i react-native-vector-icons
官方示例代码
import * as React from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
function HomeScreen() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home!</Text>
</View>
);
}
function SettingsScreen() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Settings!</Text>
</View>
);
}
const Tab = createBottomTabNavigator();
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="Settings" component={SettingsScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}
如果这个示例代码可以跑通,那就开始吧
配置底部导航
直接说不太明确,直接贴出代码,基本都可以看懂的,配合官方示例
// 路由文件,主要配置底部导航栏
import * as React from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';
// 页面栈
import HomeScreen from './screens/HomeScreen/index';
import NotifyScreen from './screens/NotifyScreen/index';
function bottomTabNavigator() {
const Tab = createBottomTabNavigator();
return (
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
switch (route.name) {
case 'Home':
iconName = 'ios-home';
break;
case 'Notify':
iconName = 'ios-planet';
break;
}
return <Ionicons name={iconName} size={size} color={color} />;
},
tabBarActiveTintColor: 'tomato',
tabBarInactiveTintColor: 'gray',
headerShown: false // 不展示标题栏
})}>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="Notify" component={NotifyScreen} />
</Tab.Navigator>
);
}
function App() {
const Stack = createNativeStackNavigator();
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="首页" component={bottomTabNavigator} />
<Stack.Screen name="通知" component={bottomTabNavigator} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
页面代码
import React, { Component } from 'react';
import { Text, View } from 'react-native';
class ScreenNotify extends Component {
render() {
return (
<View>
<Text> 我是首页 </Text>
</View>
);
}
}
export default ScreenNotify;
问题疑惑
刚开始写完代码是这个样子的,当时就懵了,这不是两个标题栏重合了,冥思苦想,百度啊,谷歌啊,没解决。
最后看官方示例,然后自己反复检查,然后看官方代码
最后原来只需要一行代码即可解决
headerShown: false // 不展示标题栏
具体代码放置位置可以看上面完整代码
加上之后的样子就好看多了
看效果
所以以后大家遇到问题,尽量还是多看文档
今天就到这里了,如果有问题或者文章有错误还请及时指正,小弟在此谢过
Comments 5