React Native 在屏幕组件外获取导航对象

And*_*rei 4 react-native react-native-navigation react-navigation react-native-push

我需要能够从不一定是屏幕组件的模块中导航和重置导航堆栈。这意味着,我不能使用:

const {navigate} = this.props.navigation;
Run Code Online (Sandbox Code Playgroud)

就我而言,当他点击推送通知时,我需要正确地将用户重定向到正确的屏幕。我只有一个回调:

onNotification: function(notification) {
    // show correct screen and reset navigation stack
}
Run Code Online (Sandbox Code Playgroud)

我只需要更多的导航灵活性。那么我该如何为我的案例做到这一点呢?

And*_*rei 5

这是我的解决方案。我为所有屏幕实现了基类。有了这个,我总是知道我在哪个屏幕上,并且可以随时获取导航对象以在需要时重定向用户:

import React, {Component} from 'react';

export default class Base extends Component {
    static screen;

    constructor(props) {
        super(props);
        Base.screen = this; 
    }

    nav() {
        return this.props.navigation;
    }
}
Run Code Online (Sandbox Code Playgroud)

在其他一些组件/模块中,我可以调用它来导航到不同的屏幕:

Base.screen.nav().navigate(...);
Run Code Online (Sandbox Code Playgroud)