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>)
}

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>)
}
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 screenuseFocuseEffect
:一個副作用掛鉤,當加載屏幕時,該掛鉤將返回已聚焦的屏幕useLinking
: handles deepLinkinguseLinking
:處理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/