如何在不使用导航道具的情况下在路线之间导航?

时间:2018-02-22 13:43:53

标签: react-native react-navigation

我正在尝试从DrawerOpen内部的屏幕(示例#3)调用StackNavigator路由(示例#1),该屏幕在{1}内呈现为<ProductStack>组件(示例#3)。

在该堆栈中,我需要一个能够访问DrawerOpen的按钮,但我在该页面上的导航无法访问该DrawerOpen路由。

有没有办法从我的应用程序的任何组件访问(并调用)任何路径,而不依赖于导航道具?

这是我的抽屉组件(示例#1):

import React, { Component } from 'react'

import { DrawerNavigator } from 'react-navigation'

import ProductEntryScreen from './../productEntry/screen'
import InvoiceInScreen from './../invoiceIn/screen'

const InvoiceInEntry = { screen: InvoiceInScreen}
const ProductEntry = {
  screen: ProductEntryScreen,
  navigationOptions: {
    title: 'Entrada de produto'
  }
}

const Drawer = DrawerNavigator({
  ProductEntry,
  InvoiceInEntry
})

export default Drawer

以下是包装器组件(示例#2,它也作为ProductEntryScreen在#1上导入):

import React, { Component } from 'react'

import {
  StackNavigator,
} from 'react-navigation'

import InfoScreen from './info/screen'
/* Other imports omitted due to brevity */

import * as ProductEntryActions from './actions'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'

const Info = {
  screen: InfoScreen,
  navigationOptions: {
    title: 'Entrada de produto'
  }
}

/* Other routes omitted due to brevity */

const ProductStack = StackNavigator({
  Info,
  /* Other routes omitted due to brevity */
},{
  initialRouteName: 'Info',
})

class ProductEntryScreen extends Component {
  componentDidMount() {
    this.props.getBlocks()
  }

  render() {
    return (
      <ProductStack />
    )
  }
}

const mapDispatchToProps = dispatch => bindActionCreators(ProductEntryActions, dispatch)

export default connect(null, mapDispatchToProps)(ProductEntryScreen)

现在屏幕(示例#3):

import React, { Component } from 'react'

/* Imports ommited */

export default class ProductEntryScreen extends Component {
  static navigationOptions = ({navigation, screenProps}) => ({
    headerLeft: (
      <MenuButton
        onClick={() => {
          // This used to work without wrapping ProductStack in a component
          // but I need it to be a component
          navigation.navigate('DrawerOpen')
        }
      />
    ),
  })

  render() {
    return (
      <View></View>
    )
  }
}

如果我在#2上export default ProductStack而没有创建组件(在componentDidMount上也失去了该功能),则导航到#3上的DrawerOpen就像魅力一样。但我需要调用该函数,并且还知道一种调用DrawerOpen的方法,而不必依赖navigation道具。

1 个答案:

答案 0 :(得分:0)

如果您正在使用redux或类似的东西,那么您可以创建一个动作来为您路由。如果没有,您可以使用NavigationActions

import { NavigationActions } from 'react-navigation';

const navigateAction = NavigationActions.navigate({
  routeName: 'Profile',
  params: {},
});

this.props.navigation.dispatch(navigateAction);