reactnavigation官方文档 依照文档说明需要安装以下依赖
npm install @react-navigation/native
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
安装主要的两个依赖
npm install @react-navigation/stack
npm install @react-navigation/bottom-tabs
这是我的项目文件目录
因为之前是个Vue开发者
,项目目录会沿用熟悉的一套
在src
目录下新建router
文件夹
里面放置index.js
,StackNavigator.js
,TabNavigator.js
三个文件夹
路由进行集中管理
集中导入所有的项目文件
const router = [
{
name: "Index", //跳转路径
title: "明知山", //头部展示标题
component: require("./TabNavigator").default,
},
//下面只需要配置非tabbar页面路径
{
name: "Detail",
title: "详情",
component: require("../views/Detail/Detail").default
},
{
name: "Life",
title: "生命周期",
component: require("../views/Life/Life").default
},
]
export default router
配置tabbar导航栏
import React from 'react';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
const Tab = createBottomTabNavigator();
import { Image, StyleSheet } from "react-native"
const tabbar = [
{
name: "首页",
component: require("../views/Index/Index").default,
icon: require("../assets/img/1.png"),
selectIcon: require("../assets/img/s1.png")
},
{
name: "我的",
component: require("../views/Mine/Mine").default,
icon: require("../assets/img/2.png"),
selectIcon: require("../assets/img/s2.png")
},
]
const TabNavigator = () => {
return (
<Tab.Navigator
tabBarOptions={{
activeTintColor: '#2C3167',
}}>
{
tabbar.map((item, index) => {
return (
<Tab.Screen key={index} name={item.name} component={item.component}
options={{
tabBarIcon: ({ focused }) => (
<Image source={focused ? item.selectIcon : item.icon} style={[styles.image]} />
),
}}
/>
)
})
}
</Tab.Navigator>
);
}
const styles = StyleSheet.create({
image: {
width: 20,
height: 20,
},
});
export default TabNavigator;
配置页面导航路由
import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import { getFocusedRouteNameFromRoute } from '@react-navigation/native';
const Stack = createStackNavigator();
import router from "./index"
const StackNavigator = () => {
//从子导航器获取路由名称
const getChildTitle = (route) => {
const routeName = getFocusedRouteNameFromRoute(route);
return routeName
}
return (
<Stack.Navigator>
{
router.map((item, index) => {
return (
<Stack.Screen key={index} name={item.name} component={item.component} options={({ route }) => ({
title: getChildTitle(route) || item.title,
headerStyle: {
backgroundColor: '#fff',
height: 40
},
headerTitleStyle: {
color: '#000',
fontSize: 15
},
// headerShown: false, //不显示头部标题
})} />
)
})
}
</Stack.Navigator>
);
}
export default StackNavigator;
导入到App.js里进行显示
import 'react-native-gesture-handler'
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import StackNavigator from "./src/router/StackNavigator"
const App = () => {
return (
<NavigationContainer>
<StackNavigator />
</NavigationContainer>
);
}
export default App;