【问题标题】:How can I pass dispatch function into Header Component?如何将调度函数传递给 Header 组件?
【发布时间】:2018-01-08 09:06:54
【问题描述】:
import React from 'react'
import {
  StackNavigator
} from 'react-navigation'

import Home from './Home'
import Detail from './Detail'
import MyIcon from './MyIcon'

export default StackNavigator({
  Home: {
    screen: Home,
    navigationOptions: {
      title: 'Foo',
      headerRight: (<MyIcon dispatch={}/>), //<- Here
    }
  },
  Detail: {
    screen: Detail,
    navigationOptions: {},
  },
})

我想在 React Navigation Option 设置中将调度函数传递给 HeaderComponent,例如 headerRight。 我该怎么做?

【问题讨论】:

  • headerRight被按下时你想从你的组件中调用dispatch函数吗?
  • 是的,没错

标签: react-native react-redux react-navigation


【解决方案1】:

您需要在headerRightcall 您的dispatch 函数,并在您的componentmounted 时使用this.props.navigation.setParams 进行设置

import React from 'react'
import {
    StackNavigator
} from 'react-navigation'

import Home from './Home'
import Detail from './Detail'
import MyIcon from './MyIcon'

export default StackNavigator({
    Home: {
        screen: Home,
        navigationOptions: ({ navigation }) => {
            title: 'Foo',
            headerRight: (<MyIcon 
                          onPress={ () => navigation.state.params.dispatch() } />)
                          // calling dispatch when headerRight icon is press
        }
    },
    Detail: {
        screen: Detail,
        navigationOptions: {},
    },
})

在你的组件中设置dispatch函数

...

//setting dispatch function to headerRight in your component
componentDidMount() {
    this.props.navigation.setParams({
        dispatch: this.dispatch.bind(this)
    });
}

dispatch() {
    // your code
}

我希望这会有所帮助!

【讨论】:

  • 太棒了!谢谢:)
猜你喜欢
  • 2017-12-29
  • 1970-01-01
  • 2016-11-30
  • 2016-04-09
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
相关资源
最近更新 更多