使用渲染中的Stack导航器从app.js导航

时间:2019-10-09 08:50:16

标签: react-native navigation navigation-drawer react-navigation

我使用https://reactnavigation.org,如果文件导航位于app.js内,我不知道如何导航...

我测试了NavigationService,但我不了解其工作原理...

我在App.js中的代码

import NavigationService from './src/utils/helpers/NavigationService';

const App = () => {

var PushNotification = require("react-native-push-notification");

  PushNotification.configure({
    onNotification: function(notification) {

        let num = 0;
        if (Platform.OS === 'ios') {
          num = notification.data.num;
        } else {
          num = notification.userInfo.num;
        }

        switch(num) {

          case 1:
            NavigationService.navigate('Scan', {a: 'a'});
            break;

          default:
            console.warn("NUMBER NOT FOUND");

        }
    }
  })

  return (
    <AppNavigator />
  );

export default App;

MainNavigation.js

const MyDrawerNavigator = createDrawerNavigator({
  Home: {
    screen: HomeScreen,
  },
  Scan: {
    screen: ScanScreen,
  },
});

export default createAppContainer(MyDrawerNavigator);

NavigationService

import { NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

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

export default {
  navigate,
  setTopLevelNavigator,
};

如何从app.js文件导航?

1 个答案:

答案 0 :(得分:1)

根据documentation

更改MainNavigation.js文件的默认导入来源

export default createAppContainer(MyDrawerNavigator);

import NavigationService from './src/utils/helpers/NavigationService';

.....

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

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