/**
* 须知:a bare React Native Project(not an Expo managed project)
*
* React官方文档:https://reactnative.dev/docs/navigation
*
* 当前文档基于6.x
* React Navigation文档:https://reactnavigation.org/docs/getting-started
*
* "@react-navigation/native": "^6.1.9",
* "@react-navigation/native-stack": "^6.9.17",
* "react": "18.2.0",
* "react-native": "0.73.2",
* "react-native-safe-area-context": "^4.8.2",
* "react-native-screens": "^3.29.0"
*/
一、基本使用
1、首先要安装(npm install 或 yarn add)
yarn add @react-navigation/native @react-navigation/native-stack
2、需要结合适配android/IOS设备屏幕的依赖才可以使用
yarn add react-native-screens react-native-safe-area-context
3、现在开始改造默认的App.tsx(新建两个组件:Home.tsx页面内容是原来的App.tsx稍微做修改、AboutUs.tsx)
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { View } from 'react-native';
import Home from './src/views/Home';
import AboutUs from './src/views/AboutUs';
const Stack = createNativeStackNavigator()
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName='Home'>
<Stack.Screen
name='Home'
component={Home}
options={{title: 'Hi!Mortal'}} />
<Stack.Screen name="AboutUs" component={AboutUs} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
2、当前是用安卓设备测试,所以按照官方文档还需要在MainActivity.kt重写onCreate方法
3、在Home.tsx组件中导航到AboutUs.tsx
如果出现错误提示,可以正常运行,但还是要统一严格使用TypeScript(暂时不用太关心navigation的来源)
方式1
方式2
可以将navigation打印出来看有哪些函数可以调用,满多API供我们调用
{"addListener": [Function addListener], "canGoBack": [Function canGoBack], "dispatch": [Function dispatch], "getId": [Function getId], "getParent": [Function getParent], "getState": [Function anonymous], "goBack": [Function anonymous], "isFocused": [Function isFocused], "navigate": [Function anonymous], "pop": [Function anonymous], "popToTop": [Function anonymous], "push": [Function anonymous], "removeListener": [Function removeListener], "replace": [Function anonymous], "reset": [Function anonymous], "setOptions": [Function setOptions], "setParams": [Function anonymous]}
加个跳转入口
到此基本的路由跳转已经完成(navigation.push、navigation.goBack、navigation.popToTop基础用法待研究)
二、页面传参数
1、可以在App.tsx里定义initialParams的类型或者不定义,这个视情况而定
2、Home.tsx里重新对navigation定义类型(这里定义了严格的类型),因为之前是any类型,所以调用是这样的navigation?.navigate(xxx)
这里只是额外多了showAppVersion、otherParams两个字段,那App.tsx里的initialParams有什么用呢?
3、接受页面传参,是用route去取值的
到这里已经完成了基础的工作准备,现在可以打印出来看route携带了哪些信息,params里可以看到多了theme字段,没错这个就是之前定义的initialParams,所以视情况而定,比如每个页面都需要相同的数据源时。
{
"key": "AboutUs-nb2KVya6DJRe_JfecBAR8",
"name": "AboutUs",
"params": {
"otherParams": "Good Good Study! Day Day Up!",
"showAppVersion": true,
"theme": "dark"
},
"path": undefined
}
4、最后贴一张效果图