Detailed explanation of the basic use of react-navigation6.x routing library

Detailed explanation of the basic use of react-navigation6.x routing library

react-native project initialization

Open cmd and cd to the folder where you want to create the rn project.

npx react-native init testRN

Here my project name is set to testRN, you can set it yourself.

Install react-native project

Connect the Android virtual machine or USB debugging real machine, cd into the created project root directory, install and start yarn android.

yarn android

After the initial installation is completed, if the mobile phone is not disconnected, you only need to enter the project app in the virtual machine or mobile phone, and then start the PC in the project root directory yarn start without installing it again. You may need to reinstall it after disconnection.

yarn start

After starting up, press r in the cmd interface to update.

react-navigation routing library installation

The content is built on Android testing, I haven't tested iOS.

Install the following packages at once.

yarn add @react-navigation/native react-native-screens react-native-safe-area-context @react-navigation/native-stack

For additional configuration of Android, modify the MainActivity.java file in testRN\android\app\src\main\java\com\testrn .

insert image description here

Code:

  import android.os.Bundle;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(null);
  }

Using the Routing Library

Modify app.js to the following code

import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
    </View>
  );
}

const Stack = createNativeStackNavigator();

function App() {
  return (
    // NavigationContainer is a container for routes, put all related content in it <NavigationContainer>
      <Stack.Navigator>
        {/* Stack.Screen is the routed window, name sets the window name for jump, and the component content of the window is placed in component */}
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

insert image description here

Route jump and route parameter transmission

import * as React from 'react';

// Add Button
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
                    
                // Add navigation parameter function HomeScreen({navigation}) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      {/* Add jump button */}
      <Button
        title="Go to Details"   
        // navigation.navigate('Details') is used to jump, where Details points to the corresponding window name
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

function DetailsScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
    </View>
  );
}

const Stack = createNativeStackNavigator();

function App() {
  return (
    // NavigationContainer is a container for routes, put all related content in it <NavigationContainer>
      <Stack.Navigator>
        {/* Stack.Screen is the routed window, name sets the window name for jump, and the component content of the window is placed in component */}
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

Set the route title

By default, the window will use name as the title, but you can also set it yourself.

<Stack.Screen name="Home" component={HomeScreen} options={{ title: 'my home'}} />

Use my home instead of Home as the navigation title.

Usually when a first-level page jumps to a second-level page, different titles may be displayed depending on the content. At this time, it is necessary to dynamically configure the title.

<Stack.Screen name="Details" component={DetailsScreen}
   options={({ route }) => ({ title: route.params.title })}
/>

Then just pass the title when jumping to the first-level page.

<Button
   title="Go to Details"
  // navigation.navigate('Details') is used to jump, where Details points to the corresponding window name
   onPress={() => navigation.navigate('Details', { title: 'Secondary Page' })}
/>

Note that if the first-level page does not pass a title, it is best to pass an empty object or set the initial value on the second-level window, otherwise an error will be reported.

You can also update the title manually using navigation.setOptions() , which modifies the properties in the options on the screen.

<Button
   title="Update the title"
   onPress={() => navigation.setOptions({ title: 'Updated!' })}
/>

Custom title component

Set the headerTitle callback to return a functional component, which can be customized and can be an image.

function LogoTitle() {
  return (
    <Image
      style={{ width: 50, height: 50 }}
      source={require('./src/img/details.png')}
    />
  );
}

<Stack.Screen name="Home" component={HomeScreen}
   options={{
     title: 'My home',
     headerTitle: (props) => <LogoTitle {...props} />
   }}
/>

Title Button

Also in the options of the screen, there is headerRight where you can put the button.

        <Stack.Screen name="Home" component={HomeScreen}
          options={{
            title: 'My home',
            headerTitle: (props) => <LogoTitle {...props} />,
            headerRight: () => (
              <Button
                onPress={() => alert('This is a button!')}
                title="Info"
                color="#fff"
              />
            ),
          }}
        />

headerBackImageSource can modify the back button image.

        <Stack.Screen name="Details" component={DetailsScreen}
          options={({ route }) => (
            {
              title: route.params.title,
              headerBackImageSource: detailsImg,
            }
          )}
        />

This is the end of this article about the basic usage of react-navigation6.x routing library. For more relevant react-navigation6.x routing library content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • React-navigation dynamically changes the content of title
  • Summary of Problems Encountered in Using React Navigation
  • React Native react-navigation navigation usage details
  • How to determine whether the user is logged in and jump to the login page in react-navigation
  • Detailed explanation of cross-tab routing processing in React Native using react-navigation
  • React Native Learning Tutorial: Detailed Explanation of Custom NavigationBar
  • React-native example of using react-navigation for page jump navigation

<<:  How to analyze MySQL query performance

>>:  Detailed explanation of the problem when combining CSS ellipsis and padding

Recommend

Method of building docker private warehouse based on Harbor

Table of contents 1. Introduction to Harbor 1. Ha...

A few things about favicon.ico (it’s best to put it in the root directory)

Open any web page: for example, http://www.baidu....

MySQL storage engine basics

In the previous article, we talked about MySQL tr...

Solution to Docker image downloading too slowly

Docker image download is stuck or too slow I sear...

mysql5.7.17 installation and configuration example on win2008R2 64-bit system

123WORDPRESS.COM has explained to you the install...

SASS Style Programming Guide for CSS

As more and more developers use SASS, we need to ...

How to implement variable expression selector in Vue

Table of contents Defining the HTML structure Inp...

Why can't the MP4 format video embedded in HTML be played?

The following code is in my test.html. The video c...

How to load the camera in HTML

Effect diagram: Overall effect: Video loading: Ph...

Example of implementing dashed border with html2canvas

html2canvas is a library that generates canvas fr...

MySQL dual-master (master-master) architecture configuration solution

In enterprises, database high availability has al...

Use semantic tags to write your HTML compatible with IE6,7,8

HTML5 adds more semantic tags, such as header, fo...

Vue implements top left and right sliding navigation

Navigation and other things are often used in dai...