How to handle click event on tab item of TabNavigator in React Native App using react-navigation?

vannguyen picture vannguyen · Aug 4, 2017 · Viewed 9.9k times · Source

I am programming React Native App. I am using react-navigation for navigating screens.

I have 2 Stack Navigators, they are stayed in a Tab Navigator. I want handle click event when I press tab item on TabBar to refresh its view.

export const HomeStack = StackNavigator({
  Home: {screen: ScreenHome},
  Detail: {screen: ScreenDetail}
})
export const UserStack = StackNavigator({
  User: {screen: ScreenUser}
})
export const Tabbar = TabNavigator({
  HomeTab: {
    screen: HomeStack,
  },
  UserTab: {
    screen: UserStack,
  }   
}, {
  tabBarComponent: ({ jumpToIndex, ...props}) => (
       <TabBarBottom
          {...props}
          jumpToIndex={(index) => {
            if(props.navigation.state.index === index) {
            props.navigation.clickButton(); //----> pass props params (code processes)
          }
          else {
            jumpToIndex(index);
          }
        }
      }
    />
   ),
   tabBarPosition: 'bottom'
});
class TabClass extends Component{
  constructor(props){
    super(props)
    this.clickButton = this.clickButton.bind(this)
  }
  clickButton(){
    console.log('click button')
  }
  render (){
    return (
      <Tabbar  clickButton={()=> this.clickButton()}/>
    )
  }
}

I want to pass clickButton() function from TabClass Component to the code which processes event click tab bar. When if(props.navigation.state.index === index), I want it will call clickButton(). I try it but it doesn't work. Is there any way to solve my matter?

I tried onNavigationStateChange(prevState, currentState).

class TabClass extends Component{
  constructor(props){
    super(props)
    this.clickButton = this.clickButton.bind(this)
  }
  clickButton(){
    console.log('click button')
  }
  _handleNavagationStateChange(prevState, currentState){
    console.log('handle navigation state change')
  }
  render (){
    return (
        <Tabbar onNavigationStateChange={(prevState, currentState) => {
          this._handleNavagationStateChange(prevState, currentState)
        }}
        clickButton={()=> this.clickButton()}
        />
    )
  }
}

However, _handleNavagationStateChange(prevState, currentState) only run when navigation state changes (for examples, if I stay at HomeTab, I click User Tab Item, this function will run; if I stay at HomeTab, I click Home Tab Item, this function will not run).

Is there any way to handle click event on tab item.

Answer

David Schumann picture David Schumann · May 24, 2018

according to the newest documentation here, you can use navigationOptions: {navigationOptions: () => doWhatever()} to handle tab bar taps.