如何在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.pswp.cn/news/390373.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390373.shtml
英文地址,請注明出處:http://en.pswp.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;按屬性&…