如何在React Native中使用react-navigation 5处理导航
React-navigation is the navigation library that comes to my mind when we talk about navigation in React Native.
當(dāng)我們談?wù)揜eact Native中的導(dǎo)航時,React-navigation是我想到的導(dǎo)航庫。
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中處理導(dǎo)航的第一個解決方案。 這部分是因為它具有一個很棒且簡單的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發(fā)行到穩(wěn)定版。 它帶有一些功能更改和新的API設(shè)計,提供了一種簡單而又不同的方法來聲明路由。
In this article, we are going to go through the new APIs and look at ways to use them in our applications.
在本文中,我們將介紹新的API,并研究在我們的應(yīng)用程序中使用它們的方法。
Originally published on saidhayani.com
最初發(fā)布于saidhayani.com
正在安裝 (Installing)
The way you install react-navigation has changed a little bet compared to previous versions (>4.x):
與以前的版本(> 4.x)相比,您安裝react-navigation的方式已發(fā)生了一些變化:
// > 4.x verions yarn add react-navigationInstalling react-navigation 5 will look like this:
安裝react-navigation 5將如下所示:
// yarn yarn add @react-navigation/native // npm npm install @react-navigation/nativeThe 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動態(tài)畫面 (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在初始化路由時引入了動態(tài)性。 以前是靜態(tài)完成的-基本上,我們必須在配置文件中定義路由。
// @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帶有動態(tài)組件。 并使導(dǎo)航更加動態(tài)。 聲明路線的新方法將非常類似于以下內(nèi)容。
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>) }This new way is dynamic, simpler to use, and is kinda similar to react-router API.
這種新方法是動態(tài)的,易于使用,并且有點類似于react-router API。
動態(tài)選項 (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.
長期以來,這一直是社區(qū)最要求的功能。 我總是遇到舊方法(靜態(tài))的問題,而且很難動態(tài)更改導(dǎo)航行為。
舊方法=> <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導(dǎo)航,我們必須定義靜態(tài)選項。 而且沒有辦法動態(tài)地改變它。
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導(dǎo)航帶有一個非常簡單的動態(tài)方法。 我們可以僅使用props將選項設(shè)置為任何屏幕。
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>) }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.
使用動態(tài)選項,我可以基于身份驗證更改標(biāo)題。 例如,如果用戶通過了身份驗證,則可以將屏幕標(biāo)題設(shè)置為用戶的用戶名,也可以更改標(biāo)題的backgroundColor。
This is more useful especially if you are using dynamic themes or if you are willing to implement dark mode in your app.
特別是在使用動態(tài)主題或愿意在應(yīng)用中實現(xiàn)暗模式時,此功能特別有用。
鉤子 (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.
到目前為止,這是我最喜歡的功能,它可以節(jié)省時間。 新的API引入了一些自定義的掛鉤來執(zhí)行某些操作。
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,則必須創(chuàng)建一些幫助程序來為我執(zhí)行此操作,類似于以下內(nèi)容。
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.
現(xiàn)在,我可以使用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做同樣的事情。 它使我們能夠訪問導(dǎo)航狀態(tài)。
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 :一個副作用掛鉤,當(dāng)加載屏幕時,該掛鉤將返回已聚焦的屏幕
useLinking: handles deepLinking
useLinking :處理deepLinking
I highly recommend that you check them out.
我強烈建議您檢查一下 。
結(jié)語 (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肯定從靜態(tài)變?yōu)閯討B(tài)。 這是一個很好的方向,它將絕對改變我們在React Native中處理導(dǎo)航的方式。 動態(tài)路線是響應(yīng)導(dǎo)航用戶的主要要求,這種新方式將幫助我們創(chuàng)造更好的用戶導(dǎo)航體驗。
您可以在此處找到有關(guān)React Native的更多內(nèi)容 (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開發(fā)人員嗎? 打我 。
翻譯自: https://www.freecodecamp.org/news/introducing-react-navigation-5/
總結(jié)
以上是生活随笔為你收集整理的如何在React Native中使用react-navigation 5处理导航的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到死鸡是什么意思周公解梦
- 下一篇: 文章中嵌入代码块_如何在您的文章中嵌入多