Initiate screen switching from anywhere when using React Navigation

Introduction

In general, when using React Navigation, we always initiate navigation from inside a screen (or route) component that belongs to the React Navigation navigation stack. In this case, since we have it this.props.navigationavailable, it is not a problem to initiate navigation. . But in some cases, for example, we encapsulate general business logic and need to initiate screen switching in these logics, and these encapsulated logics do not belong to any screen component of the React Navigation navigation stack, but are located in some other class. , then what should we do at this time?

The official website of React Navigation provides a method. The idea is to record the navigation stack used in a global variable, and then encapsulate a navigation service, which uses this global variable of the navigation stack to initiate screen switching. We demonstrate this method using example code.

Navigation service package

import {NavigationActions} from 'react-navigation';

// reference : https://reactnavigation.org/docs/navigating-without-navigation-prop.html
// 该服务作为单例模式使用,用于记录顶层导航器,这样在应用的各个部分,各个屏幕组件内部,
// 或者任何屏幕组件之外的其他服务逻辑/工具逻辑中,都可以使用该服务的 navigate() 方法导航到目标屏幕,
// 类似于在某个屏幕组件中使用 this.props.navigation.navigate 函数进行的屏幕切换

// 用于记录所使用的导航器
let _navigator;


/**
 * 记录所使用的导航器
 * @param navigatorRef
 */
function setTopLevelNavigator(navigatorRef) {
    _navigator = navigatorRef;
}

/**
 * 导航到目标路由/屏幕
 * @param routeName
 * @param params
 */
function navigate(routeName, params) {
    _navigator.dispatch(
        NavigationActions.navigate({
            type: NavigationActions.NAVIGATE,
            routeName,
            params,
        })
    );
}

export default {
    navigate,
    setTopLevelNavigator,
};

Record the navigation stack used in the application component

import React, {Component} from 'react';
import {StackNavigator} from 'react-navigation';
import navigationService from './NavigationService';

const rootStack = StackNavigator({
// ... 省略具体实现
});

export default class App extends Component {
// ... 其他代码
    render() {
        return <rootStack ref={navigatorRef => {
            navigationService.setTopLevelNavigator(navigatorRef);
        }}
        />;
    }
}
// ... 其他代码

Use Navigation Services to Initiate Screen Switches Anywhere

// 比如在某个服务逻辑封装类中
import navigationService from "../NavigationService";


navigationService.navigate('LoginScreen', {})

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325591331&siteId=291194637