React Navigation Using Navigation

In a web browser, you can use anchor tags to link to different pages. When a user clicks a link, the URL is pushed to the browser 历史记录堆栈. When the user presses the back button, the browser pops the item from the top of the history stack, so the active page is now the previously visited page. React Native does not have a built-in concept of a global history stack like a web browser, and React Navigation is a tool that helps us implement navigation management.

React Navigation's stack navigator provides a way for your application to transition between screens and manage navigation history. If your app only uses a stack navigator, it's conceptually similar to how a web browser handles navigation state - as the user interacts with it, your app pushes and pops items from the navigation stack, which Causes the user to see a different screen. React Navigation's stack navigator provides the gestures and animations you'd expect when navigating between routes in the stack on Android and iOS.

Install Stack Navigator

In the previous article, we installed the building blocks and basic modules of the navigator. When we need the stack navigator, we need to install the following packages:

npm install @react-navigation/native-stack

Create stack

First let's look at a simple example:

import React from "react";
import Home from "./page/Home";
import {
    
     NavigationContainer } from "@react-navigation/native";
import {
    
     createNativeStackNavigator } from "@react-navigation/native-stack";

const App: React.FC = () => {
    
    
  const Stack = createNativeStackNavigator();

  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home Page" component={
    
    Home} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

The effect after running is as follows:

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-uDUJWkBl-1693035587956)(./images/ReactNavigation.png “ReactNavigation1”)]

From the above example we can see that we use a createNativeStackNavigator()method to create a navigation stack. createNativeStackNavigatoris a function that returns an object containing 2 properties: Screenand Navigator. They are both React components used to configure the navigator. The Navigator should contain the Screen element as its child element to define the routing configuration.

NavigationContainerIs a component that manages the navigation tree and contains navigation state. This component must wrap all navigator structures. Typically, we render this component at the root of the application, which is usually bound from App.tsx.

Configure a second navigation route

Based on the above code, change it to the following code:

<Stack.Navigator initialRouteName="Home">
  <Stack.Screen name="Home" component={
    
    HomeScreen} />
  <Stack.Screen name="Details" component={
    
    DetailsScreen} />
</Stack.Navigator>

Our stack now has two routes, a Home route and a Details route. Routes can be specified using components Screen. The Screen component accepts a name prop corresponding to the route name we will use for navigation, and a component prop corresponding to the component it will render.

Now in the route navigation, the Home route corresponds to the component Home, and the Details route corresponds to the component DetailsScreen.

Note:
Stack.Screen In the component that componentaccepts components, not rendering functions, do not pass inline functions (eg: component={() => <component/>}), otherwise your component will unload and re-render when the parent component re-renders installed, thus losing all state. See Passing additional props for alternatives.

Stack.Screen Description

Stack.ScreennameIn addition to and attributes, components componentcan also be used optionsto set other parameter attributes. Specific examples are as follows:

<Stack.Navigator>
  <Stack.Screen
    name="Home Page"
    component={
    
    Home}
    options={
    
    {
    
     title: "Overview" }}
  />
  <Stack.Screen name="Detail Page" component={
    
    ReviewDetails} />
</Stack.Navigator>

Sometimes we may want to pass additional parameters to the corresponding component. We have the following two ways to achieve this:

  • Use a React context and wrap the navigator with a context provider to pass data to the screen (recommended)

  • Use a render callback for the screen instead of specifying componentprop:

    <Stack.Screen name="Home">
      {
          
          (props) => <HomeScreen {
          
          ...props} extraData={
          
          someData} />}
    </Stack.Screen>
    

Navigation toggle

First let's give an example:

export default function Home(props: {
    
     navigation: any }) {
    
    
  return (
    <View>
      <Text>Home</Text>
      <Button
        title="切换到详情页"
        onPress={
    
    () => props.navigation.navigate("Detail Page")}
      />
    </View>
  );
}

After implementing the above code, the page will switch to the details page when we click the button. Next we will explain the specific parameters:

  • navigation

    Native stack navigator object data, and each component will have this property

  • navigate(‘Detail Page’)

    Calling this function can help us jump to the page of the corresponding name component.

**Note:** If we navigation.navigatejump to a page without a defined route, the corresponding error message will be reported in the development environment, but there will be no reflection in the packaged production environment.

routing loop

Now that we have two routes, what will happen after we enter the details page again and navigate to the details page again? Let us use the following code to verify it:

export default function ReviewDetails(props: {
    
     navigation: any }) {
    
    
  return (
    <View>
      <Text>ReviewDetails</Text>
      <Button
        title="切换到详情页"
        onPress={
    
    () => props.navigation.navigate("Detail Page")}
      />
    </View>
  );
}

After running the above code, you will find that when you click 切换到详情页, no operation will occur, and after clicking return, we can directly return to the home page at once. Because when we click on the home page 切换到详情页, our routing line will jump to the details page. When we click 切换到详情页, the program will determine whether it is on the details page routing line. If it is, it will not do anything.

Assuming that we actually want to add a new details page route regardless of the existing navigation history, we can use pushto achieve this. Specific examples are as follows:

<View>
  <Text>ReviewDetails</Text>
  <Button
    title="切换到详情页"
    onPress={
    
    () => props.navigation.push("Detail Page")}
  />
</View>

Each time you call push we add a new route to the navigation stack. When you call navigate for the first time, it will try to find an existing route with that name and only push a new route if there is no route on the stack yet.

Programmatic navigation

Sometimes we may encounter a situation where the head navigation does not have a return button. In this case, we can use goBack()methods to implement the function of returning to the previous level route. The specific code examples are as follows:

<Button title="返回上一页" onPress={
    
    () => props.navigation.goBack()}></Button>

Also, we want to clear all routing information and return to the first page. The specific code is as follows:

<Button
  title="清除所有堆栈信息返回首页"
  onPress={
    
    () => props.navigation.popToTop()}
></Button>

Guess you like

Origin blog.csdn.net/qq_33003143/article/details/132512291