How to pass send function to header component?

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: {},
  },
})

I want to pass a submit function to a HeaderComponent, like headerRight, in setting the React Navigation Option parameter. How can i do this?

+4
source share
1 answer

You need callyour function dispatchin headerRightand set when your componentis equal mountedusingthis.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: {},
    },
})

Define a dispatchfunction in your component

...

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

dispatch() {
    // your code
}

Hope this helps!

+1
source

Source: https://habr.com/ru/post/1691868/


All Articles