在反应导航中,是否有 this.props.navigation.dispatch() 不使用 this.props.navigation 道具的等效项?

In react-navigation, is there an equivalent to this.props.navigation.dispatch() without using the this.props.navigation prop?

我看到下一个要发布的 react-navigation 版本会有 useNavigation() 钩子,但是 react-navigation@4.x 有没有办法有效地使用 this.props.navigation.dispatch()无需使用 this.props?

您可以将 react-navigation-hooks 库与 React Navigation 4 一起使用。

import { useNavigation } from 'react-navigation-hooks';

function MyComponent() {
  const navigation = useNavigation();

  // ...
}

您还可以使用主包中的 withNavigation HOC:https://reactnavigation.org/docs/en/with-navigation.html

我自己想出了一个基于修改 a recommended approach from the official react-navigation 4.x docs 的解决方案。该方法涉及从应用程序的堆栈导航器中创建导航 "app container" 组件并创建对该容器的引用。然后,该引用由中介导航服务对象(我在这里称之为 NavigationService)使用,可以在我的代码库中的任何地方导入和使用。

// App.js

import { createStackNavigator, createAppContainer } from 'react-navigation';
import NavigationService from './NavigationService';
import HomeScreen from "./HomeScreen";

const TopLevelNavigator = createStackNavigator({
  ...
  Home: {
    screen: HomeScreen,
    defaultNavigationOptions: { gesturesEnabled: isBackGestureEnabled }
  }
  ...
});

const AppContainer = createAppContainer(TopLevelNavigator);

export default class App extends React.Component {
  // ...

  render() {
    return (
      <AppContainer
        ref={navigatorRef => {
          NavigationService.setTopLevelNavigator(navigatorRef);
        }}
      />
    );
  }
}

我想要的调度操作定义如下(这里我创建了用于添加到我的导航堆栈和重置导航堆栈的方法)。 (这与 react-navigation 文档的建议不同;我不得不使用 _navigator.currentNavProp.dispatch() 而不是 _navigator.dispatch(),这对我来说不存在。)

// NavigationService.js

import { NavigationActions, StackActions } from "react-navigation";

var _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.currentNavProp.dispatch(
    NavigationActions.navigate({
      routeName,
      params
    })
  );
}

function navigationReset(routeName) {
  const resetAction = StackActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({ routeName })]
  });
  _navigator.currentNavProp.dispatch(resetAction);
}

export default { navigate, navigationReset, setTopLevelNavigator };

现在我可以在我的任何其他 JavaScript 文件中使用它,无论它们是否是 React 组件。

// anyOtherFile.js

import NavigationService from './NavigationService';

...
NavigationService.navigationReset("Home");
// or
NavigationService.navigate("Home");
...