如何在React Native中使用react-navigation 5处理导航

React-navigation is the navigation library that comes to my mind when we talk about navigation in React Native.

当我们谈论React Native中的导航时,React-navigation是我想到的导航库。

I'm a big fan of this library and it's always the first solution I use to handle navigation in React Native. This is in part becausae it has an awesome and easy API and is very customizable.

我是这个库的忠实拥护者,它始终是我用来在React Native中处理导航的第一个解决方案。 这部分是因为它具有一个很棒且简单的API,并且非常可定制。

I'm writing this article because version 5 just went from beta to stable. It comes with some feature changes and a new API design that provides a simple and different way to declare routes.

我写这篇文章是因为版本5刚从Beta发行到稳定版。 它带有一些功能更改和新的API设计,提供了一种简单而又不同的方法来声明路由。

In this article, we are going to go through the new APIs and look at ways to use them in our applications.

在本文中,我们将介绍新的API,并研究在我们的应用程序中使用它们的方法。

Originally published on saidhayani.com

最初发布于saidhayani.com

正在安装 (Installing)

The way you install react-navigation has changed a little bet compared to previous versions (>4.x):

与以前的版本(> 4.x)相比,您安装react-navigation的方式已发生了一些变化:

// > 4.x verions
yarn add react-navigation

Installing react-navigation 5 will look like this:

安装react-navigation 5将如下所示:

// yarn
yarn add @react-navigation/native
// npm
npm install @react-navigation/native

The latest versions of react-navigation use many third party library like react-native-gesture-handler for animation and handling transitions. So you always need to install those libraries.

最新版本的react-navigation使用许多第三方库(例如react-native-gesture-handler)进行动画和处理过渡。 因此,您始终需要安装这些库。

// yarn
yarn add react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
// npm
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view

动态画面 (Dynamic screens)

The new API introduces dynamism in initializing routes. Previously it was done statically - basically, we had to define our Routes in a config file.

新的API在初始化路由时引入了动态性。 以前是静态完成的-基本上,我们必须在配置文件中定义路由。

// @flow
import React from "react";import { createAppContainer, createSwitchNavigator } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";/** ---------Screens----------- */
// import LaunchScreen from "../Containers/LaunchScreen";
import HomeScreen from "../Containers/HomeScreen";import ProfileScreen from "../Containers/ProfileScreen";
import LoginScreen from "../Containers/LoginScreen";const StackNavigator = createStackNavigator({initialRouteName: "Home"},{Home: {screen: HomeScreen},Login: {screen: LoginScreen,headerMode: "none",},Profile: {screen: ProfileScreen});export default createAppContainer(StackNavigator);

The new API comes with dynamic components. and made the navigation to be more dynamic. The new way to declare the Routes will be much like the following.

新的API带有动态组件。 并使导航更加动态。 声明路线的新方法将非常类似于以下内容。

import React from "react"
import { SafeAreaView, StyleSheet, View, Text, StatusBar } from "react-native"import { NavigationContainer } from "@react-navigation/native"
import { createStackNavigator } from "@react-navigation/stack"const App: () => React$Node = () => {return (<><StatusBar barStyle="dark-content" /><SafeAreaView style={styles.containerStyle}><AppNavigation /></SafeAreaView></>)
}
const Stack = createStackNavigator()
const AppNavigation = () => {return (<NavigationContainer><Stack.Navigator initialRouteName="home"><Stack.Screen name="home" component={HomeScreen} /></Stack.Navigator></NavigationContainer>)
}
const HomeScreen = () => {return (<View style={styles.containerStyle}><Text style={styles.title}>Home Screen</Text></View>)
}

react-navigation5-demo

This new way is dynamic, simpler to use, and is kinda similar to react-router API.

这种新方法是动态的,易于使用,并且有点类似于react-router API。

动态选项 (Dynamic options)

This has been the most requested feature by the community for a long time. I always had issues with the old method (static) and it was really hard to change the navigation behavior dynamically.

长期以来,这一直是社区最要求的功能。 我总是遇到旧方法(静态)的问题,而且很难动态更改导航行为。

旧方法=> <4.x (The old method => < 4.x)

With older versions of react-navigation we had to define static options. And there was no way to change this dynamically.

对于旧版本的React导航,我们必须定义静态选项。 而且没有办法动态地改变它。

static navigationOptions = {title: "Sign In",header: null,mode: "modal",headerMode: "none"};

新方法(第5版) (The new method (version 5))

React-navigation comes with a dynamic method which is quite simple. We can set the options to any screen using just props.

React导航带有一个非常简单的动态方法。 我们可以仅使用props将选项设置为任何屏幕。

const AppNavigation = ({}) => {let auth = {authenticated: true,user: {email: "user@mail.com",username: "John",},}let ProfileScreenTitle = auth.authenticated ? auth.user.username : "Profile"return (<NavigationContainer><Stack.Navigator initialRouteName="Home"><Stack.Screen name="Home" component={HomeScreen} /><Stack.Screenname="Profile"component={ProfileScreen}options={{title: ProfileScreenTitle,headerTintColor: "#4aa3ba",headerStyle: {backgroundColor: darkModeOn ? "#000" : "#fff",},}}/><Stack.Screen name="About" component={AboutScreen} /></Stack.Navigator></NavigationContainer>)
}

react-navigation-header

With dynamic options, I can change the title based on authentication. For example if the user is authenticated, I can set the screen title to be the user’s username, or I can change the backgroundColor for the header.

使用动态选项,我可以基于身份验证更改标题。 例如,如果用户通过了身份验证,则可以将屏幕标题设置为用户的用户名,也可以更改标题的backgroundColor。

This is more useful especially if you are using dynamic themes or if you are willing to implement dark mode in your app.

特别是在使用动态主题或愿意在应用中实现暗模式时,此功能特别有用。

钩子 (Hooks)

This is my favorite feature so far, and it’s a time-saver. The new API introduced some custom hooks to perform certain actions.

到目前为止,这是我最喜欢的功能,它可以节省时间。 新的API引入了一些自定义的挂钩来执行某些操作。

In previous versions, for example, if I had to get the currentName of the active screen, I had to create some helpers to do that for me pretty much like the following.

例如,在以前的版本中,如果必须获取活动屏幕的currentName,则必须创建一些帮助程序来为我执行此操作,类似于以下内容。

export function getCurrentRouteName(): string | null {const tag = "[getCurrentRouteNameSync] "const navState = getStore().getState().navconst currentRoute = getActiveRouteState(navState)console.log(tag + " currentRoute > ", currentRoute)return currentRoute && currentRoute.routeName ? currentRoute.routeName : null
}

The hooks API helps me avoid all these things and makes it easier for me to access the Navigation API with one single line using a hook.

钩子API可以帮助我避免所有这些事情,并使我更容易使用钩子在一行中访问Navigation API。

Now I can easily get the RouteName using useRoute Hook.

现在,我可以使用useRoute Hook轻松获取useRoute

import { useRoute } from "@react-navigation/native"
const AboutScreen = ({ navigation }) => {const route = useRoute()return (<Viewstyle={{justifyContent: "space-around",flex: 1,alignItems: "center",}}>{/*    Display the RouteName here */}<Text style={styles.title}>{route.name}</Text></View>)
}

We can do the same thing with the useNavigationState Hook. It gives us access to the navigation state.

我们可以使用useNavigationState Hook做同样的事情。 它使我们能够访问导航状态。

const navigationState = useNavigationState(state => state)
let index = navigationState.index
let routes = navigationState.routes.length
console.log(index)
console.log(routes)

React-navigation offers other hooks as well, for example:

React-navigation也提供其他钩子,例如:

  • useFocuseEffect : a side effect hook that, when the screens are loaded, returns the focused screen

    useFocuseEffect :一个副作用挂钩,当加载屏幕时,该挂钩将返回已聚焦的屏幕

  • useLinking: handles deepLinking

    useLinking :处理deepLinking

I highly recommend that you check them out.

我强烈建议您检查一下 。

结语 (Wrapping Up)

The new react-navigation API definitely moves from static to dynamic. It’s a great direction that will absolutely change the way we handle navigation in React Native. Dynamic routes were a major request by react-navigation users, and this new way will help us create a better user navigation experience.

新的react-navigation API肯定从静态变为动态。 这是一个很好的方向,它将绝对改变我们在React Native中处理导航的方式。 动态路线是响应导航用户的主要要求,这种新方式将帮助我们创造更好的用户导航体验。

您可以在此处找到有关React Native的更多内容 (You can find more content about React Native here)

Thanks for reading

谢谢阅读

  • Twitter

    推特

  • GitHub

    的GitHub

  • Join the mail-list

    加入邮件列表

Looking for a React Native developer for your project? Hit me up.

在为您的项目寻找React Native开发人员吗? 打我

翻译自: https://www.freecodecamp.org/news/introducing-react-navigation-5/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/390373.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

flask内置session原理

内置session原理 请求到来 当请求进来之后&#xff0c;先执行Flask对象的 __call__ 方法 def wsgi_app(self, environ, start_response):# 获取请求相关数据&#xff0c;并进行封装和加工ctx self.request_context(environ)# 将请求消息推送到堆栈中&#xff0c;并执行 open_s…

指针3

#include <stdio.h>/* 2018-05-28 如何通过被调函数修改主调函数普通变量的值1&#xff0c;实参必须为该普通变量的地址2,形参必须为指针变量3&#xff0c;在背调函数中通过*形参名 。。。。。的方式就可以修改主调函数相关变量的值*/f(int *i,int *j) {*i 4;*j 5;ret…

面试系统设计_系统设计面试问题–您应该知道的概念

面试系统设计You may have heard the terms "Architecture" or "System Design." These come up a lot during developer job interviews – especially at big tech companies.您可能已经听说过“架构”或“系统设计”这两个术语。 在开发人员工作面试中&…

8597 石子划分问题 dpdp,只考虑第一次即可

8597 石子划分问题 时间限制:500MS 内存限制:1000K提交次数:155 通过次数:53 题型: 编程题 语言: G;GCC;VC Description 给定n个石子&#xff0c;其重量分别为a1,a2,a3,...,an。 要求将其划分为m份&#xff0c;每一份的划分费用定义为这份石子中最大重量与最小重量差的平方。…

文章中嵌入代码块_如何在您的文章中嵌入多项选择测验问题

文章中嵌入代码块In my experience, supplementing study with practical exercises greatly improves my understanding of a topic. This is especially true when I can test my knowledge as I go and receive instant feedback for each question.以我的经验&#xff0c;通…

mysql免安装版配置

1.官网下载https://dev.mysql.com/downloads/mysql/ 2.将下载好的压缩包mysql-5.7.20-winx64.zip解压。 3.mysql解压后&#xff0c;设置.ini文件&#xff0c;在加压后的路径中加一个my.ini文件 配置如下内容&#xff1a; # 设置mysql客户端默认字符集 default-character-setutf…

各种IE(IE6-IE10)兼容问题一行代码搞定

x-ua-compatible 用来指定IE浏览器解析编译页面的model x-ua-compatible 头标签大小写不敏感&#xff0c;必须用在 head 中&#xff0c;必须在除 title 外的其他 meta 之前使用。 1、使用一行代码来指定浏览器使用特定的文档模式。 <meta http-equiv"x-ua-compatible&q…

802. 找到最终的安全状态

在有向图中&#xff0c;以某个节点为起始节点&#xff0c;从该点出发&#xff0c;每一步沿着图中的一条有向边行走。如果到达的节点是终点&#xff08;即它没有连出的有向边&#xff09;&#xff0c;则停止。 对于一个起始节点&#xff0c;如果从该节点出发&#xff0c;无论每…

元类型与类型的区别

元类型是指所有类型的类型。 元类型只能类型出现在类型标示位&#xff1b; 类型即能作为类型存在&#xff0c;出现在类型标示位&#xff1b; 也能作为变量存在&#xff0c;出现在元类型的变量位。 http://www.swift51.com/swift2.0/chapter3/03_Types.html#type_inheritance_cl…

css 动画使用_如何在CSS中使用动画

css 动画使用使用CSS动画 (Using CSS Animations) CSS animations add beauty to the webpages and make transitions from one CSS style to the other beautiful.CSS动画可以使网页更加美观&#xff0c;并可以从一种CSS样式过渡到另一种CSS样式。 To create a CSS animation…

第01章—快速构建

spring boot 系列学习记录&#xff1a;http://www.cnblogs.com/jinxiaohang/p/8111057.html 码云源码地址&#xff1a;https://gitee.com/jinxiaohang/springboot 一、Spring Initializr 使用教程 &#xff08;IntelliJ IDEA&#xff09; 具体步骤&#xff1a; 1、打开IDEA &am…

看板和scrum_看板VS Scrum-如何变得敏捷

看板和scrumScrum and Kanban are the two most popular project management techniques today in business. As a developer, I think its important to understand these processes as you will likely be heavily involved in them if you are part of a team. By understan…

JS之Promise

开胃菜&#xff0c;先做如下思考&#xff1a; Promise 有几种状态&#xff1f;Promise 状态之间可以转化吗&#xff1f;Promise 中的异常可以被 try...catch 捕获吗&#xff1f;Promise前世 callback hell 大家都知道JS是异步操作&#xff08;执行&#xff09;的&#xff0c;在…

鱼眼镜头的distortion校正【matlab】

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 作者&#xff1a;WWC %%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% 功能&#xff1a;畸变矫正 clc; clear; close all; %% 读取图像 Aimread(D:\文件及下载相关\图片\distortion2.jpg)…

web后端开发学习路线_学习后端Web开发的最佳方法

web后端开发学习路线My previous article described how you can get into frontend development. It also discussed how the front end can be a place filled with landmines – step in the wrong place and youll be overwhelmed by the many frameworks of the JavaScrip…

C# 使用WinApi操作剪切板Clipboard

前言&#xff1a; 最近正好写一个程序&#xff0c;需要操作剪切板 功能很简单&#xff0c;只需要从剪切板内读取字符串&#xff0c;然后清空剪切板&#xff0c;然后再把字符串导入剪切板 我想当然的使用我最拿手的C#来完成这项工作&#xff0c;原因无他&#xff0c;因为.Net框架…

聊聊spring cloud gateway的XForwardedHeadersFilter

序 本文主要研究spring cloud gateway的XForwardedHeadersFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC1-sources.jar!/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java Configuration ConditionalOnProperty(name "sp…

node缓冲区_Node.js缓冲区介绍

node缓冲区什么是缓冲液&#xff1f; (What are Buffers?) Binary is simply a set or a collection of 1 and 0. Each number in a binary, each 1 and 0 in a set are called a bit. Computer converts the data to this binary format to store and perform operations. Fo…

专访赵加雨:WebRTC在网易云信的落地

去年的这个时候&#xff0c;在市面上公开表示使用WebRTC的公司还没几家&#xff0c;但2018年以来&#xff0c;宣布采用或支持WebRTC的公司已经越来越多。实时音视频提供商网易云信也在自研的NRTC中集成了WebRTC。在他们眼里&#xff0c;2017年是WebRTC的转折之年&#xff0c;而…

html/css杂题

1、css选择器&#xff1a;详细&#xff08;http://www.ruanyifeng.com/blog/2009/03/css_selectors.html&#xff09; 派生选择器&#xff1a;按标签 类别选择器&#xff1a;按class ID选择器&#xff1a;按ID 通用选择器&#xff1a;* 匹配所有 属性选择器&#xff1a;按属性&…