This is the 9th day of my participation in the August More Text Challenge. For details, see:August is more challenging

The basic use

Set up the project

$ npx react-native init musicqq --template react-native-template-typescript
Copy the code

The installation

$ npm install @react-navigation/native
or
$ yarn add @react-navigation/native
Copy the code

After the above command is executed successfully, the navigation core component library is installed, but the navigation process involves gesture response, animation interaction, native compatibility, etc. So the next step is to install some third-party dependencies that support these operations.

$ npm i react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
or
$ yarn add react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
Copy the code

React Native version above 0.6 does not need manual link, React Native will automatically link. But you still need to install it manually on iOS; Go to the ios folder and run the command pod install(if cocoapods is already installed).

In a Web browser, you can use the anchor () tag to link to different pages. When the user clicks the link, the URL is pushed to the browser history stack. 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 one that was previously visited. React Native doesn’t have a built-in API like web browsers do; React Navigation’s stack navigator provides a way to switch between and manage Navigation history. If your application uses only one stack navigator, it is conceptually similar to the way a Web browser handles navigation state — when the user interacts with the application, your application pushes and pops items from the navigation stack, which causes the user to see different view contents. One key difference between how this works in a web browser and React Navigation is that React Navigation’s stack navigator provides gestures and animations so you can navigate the routes in the stack on Android and iOS; Install the @React-navigation /stack navigation component

$ yarn add @react-navigation/stack
Copy the code

Achieve Tab interface switch, interface navigation

API definition: StackNavigator(RouteConfigs, StackNavigatorConfig), TabNavigator(RouteConfigs, TabNavigatorConfig)

  • Install dependencies:

    $ yarn add @react-navigation/bottom-tabs
    Copy the code
  • Create a Tab

    // The parameter list of the TAB button
    export type BottomTabParamList = {
        Home: undefined;
        List: undefined;
        Found: undefined;
        Me: undefined;
    };
    
    // Tab contains the Navigator and Screen
    const Tab = createBottomTabNavigator<BottomTabParamList>();
    Copy the code
  • Import components and write routing configurations

/ /...
import Home from '.. /pages/home/Home';
import List from '.. /pages/list/List';
import Found from '.. /pages/found/Found';
import Me from '.. /pages/me/Me';

// ...

<Tab.Navigator
    tabBarOptions={{
      activeTintColor: '#f86442', / / modifytabbarActivate color}}>
    <Tab.Screen
        name="Home"
        component={Home}
        options={{ tabBarLabel:}} />
    <Tab.Screen
        name="List"
        component={List}
        options={{ tabBarLabel:}} />
    <Tab.Screen
        name="Found"
        component={Found}
        options={{ tabBarLabel:'discover'}} />
    <Tab.Screen
        name="Me"
        component={Me}
        options={{ tabBarLabel:'my'}} />
</Tab.Navigator>

// ...
Copy the code

Normally, there will be four TAB buttons at the bottom of the page to switch to the corresponding page; But after the switch found that the top of the title is “home”, there is no change, then the top of the title switch;

// The type of the route
type Route = RouteProp<RootStackParamList, 'BottomTabs'> & { state? : TabNavigationState<BottomTabParamList>; };// Define the component attribute type
interface IProps {
    navigation: RootStackNavigation;
    route: Route;
}

// Get the title of each page
getHeaderTitle(route: Route): string {
  	// Enter the route of the current page and get the name of the route; If not, default Home
    const routeName = getFocusedRouteNameFromRoute(route) ?? 'Home';

    switch (routeName) {
        case 'Home':
        		return 'home';
        case 'List':
        		return 'list';
        case 'Found':
        		return 'found';
        case 'Me':
        		return 'I';
        default:
        		return 'home'; }}componentDidUpdate() {
    const { navigation, route } = this.props;
    navigation.setOptions({
      	headerTitle: this.getHeaderTitle(route),
    });
}
Copy the code

In this way, the complete header title switch is realized. The complete code is as follows:

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import React, { Component } from 'react';
import {
   getFocusedRouteNameFromRoute,
   RouteProp,
   TabNavigationState,
} from '@react-navigation/native';
import { RootStackNavigation, RootStackParamList } from './index';
import Home from '.. /pages/home/Home';
import List from '.. /pages/list/List';
import Found from '.. /pages/found/Found';
import Me from '.. /pages/me/Me';

export type BottomTabParamList = {
     Home: undefined;
     List: undefined;
     Found: undefined;
     Me: undefined;
};

const Tab = createBottomTabNavigator<BottomTabParamList>();

type Route = RouteProp<RootStackParamList, 'BottomTabs'> & { state? : TabNavigationState<BottomTabParamList>; };interface IProps {
   navigation: RootStackNavigation;
   route: Route;
}

export default class BottomTabs extends Component<IProps> {
 // Get the title of each page
 getHeaderTitle(route: Route): string {
     const routeName = getFocusedRouteNameFromRoute(route) ?? 'Home';

     switch (routeName) {
         case 'Home':
             return 'home';
         case 'List':
             return 'list';
         case 'Found':
             return 'found';
         case 'Me':
             return 'I';
         default:
             return 'home'; }}componentDidUpdate() {
     const { navigation, route } = this.props;
     navigation.setOptions({
         headerTitle: this.getHeaderTitle(route),
     });
 }
 render() {
     return (
         <Tab.Navigator
             tabBarOptions={{
                 activeTintColor: '#f86442', / / modifytabbarActivate color}}>
             <Tab.Screen
                 name="Home"
                 component={Home}
                 options={{ tabBarLabel:}} />
             <Tab.Screen
                 name="List"
                 component={List}
                 options={{ tabBarLabel:}} />
             <Tab.Screen
                 name="Found"
                 component={Found}
                 options={{ tabBarLabel:'discover'}} />
             <Tab.Screen
                 name="Me"
                 component={Me}
                 options={{ tabBarLabel:'my'}} />
        </Tab.Navigator>); }}Copy the code

StackNavigator also provides the onNavigationStateChange callback method to listen for navigation state changes. Realized the interface jump and switch, then it is time to increase the feelings between the next interface, to see how to achieve the interface between the transmission value and value.

Jump, transfer, and value between interfaces

When the interface component is injected into StackNavigator, the interface component is given the navigation property, which means that the interface component can be retrieved and performed with this.props. Navigation.

The navigation property provides a number of functions to simplify interinterface operations. A few are simple:

  • Navigate between interfaces using the NAVIGATE function:

    const { navigation } = this.props;
    navigation.navigate('Detail'); // Go to the details page
    Copy the code

    Parameter is the name of the interface component when we register it in StackNavigator. It is also possible to return from the current page to the previous page:

    const { navigation } = this.props;
    navigation.goBack(); // Return to the previous page
    Copy the code
  • Value passed when jumping:

    const { navigation } = this.props;
    navigation.navigate('Detail', { topId: 'see3x5dfw6' }); // Route parameters
    Copy the code

    The first parameter is also the name of the interface component to jump to, and the second parameter is the parameter to be passed. Topid can be understood as key, followed by the parameter to be passed.

  • Obtain route parameters:

    const { topId } = this.props.route.params; / / get topId
    Copy the code

    Take the passed parameter, followed by the key value, through route.params. Here is topId.