【笔记】React-Native Navigation页面导航

/**
* 须知: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 (
    
      
        
        
      
    
  );
}

export default App;

2、当前是用安卓设备测试,所以按照官方文档还需要在MainActivity.kt重写onCreate方法

【笔记】React-Native Navigation页面导航_第1张图片

3、在Home.tsx组件中导航到AboutUs.tsx

如果出现错误提示,可以正常运行,但还是要统一严格使用TypeScript(暂时不用太关心navigation的来源)

【笔记】React-Native Navigation页面导航_第2张图片

方式1

【笔记】React-Native Navigation页面导航_第3张图片

方式2

【笔记】React-Native Navigation页面导航_第4张图片

可以将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]}

加个跳转入口

到此基本的路由跳转已经完成

二、页面传参数

你可能感兴趣的:(React-Native,react,native,react.js,javascript)