如何在React Navigation中从tabBarOnPress调用自定义函数

时间:2019-01-03 19:50:37

标签: javascript reactjs react-native react-navigation

当我按下某个标签将哪个routeName标签存储到Redux中时,我需要启动自定义功能。

通常,您会使用this.myFuncthis.props.myFunc来引用该函数。但是,我似乎无法弄清楚如何通过tabBarOnPress中的createBottomTabNavigator访问函数。这有可能吗?

有人有什么想法吗?

const AppStack =  createBottomTabNavigator({
  Home: {screen: HomeStack},
  Requests: {screen: RequestsStack}
}, {
  navigationOptions: ({navigation}) => ({
    tabBarOnPress: ({navigation, defaultHandler}) => {

      const { state } = navigation;

      if(state.routes){
        if(state.routes[0].routeName === 'home'){

          // need to call custom function here

        } else if(state.routes[0].routeName === 'requests'){

          // need to call custom function here

        }
      }

      defaultHandler();
    }
  })
})




const Root = createSwitchNavigator({
  Auth: AuthStack,
  App: AppStack,
});

1 个答案:

答案 0 :(得分:0)

在组件中对“ this”的引用如此之多,我脑子发疯了,因为我可以在不引用“ this”的情况下调用函数。

我能够在下面进行此操作

const AppStack =  createBottomTabNavigator({
  Home: {screen: HomeStack},
  Requests: {screen: RequestsStack}
}, {
  navigationOptions: ({navigation}) => ({
    tabBarOnPress: ({navigation, defaultHandler}) => {

      const { state } = navigation;

      if(state.routes){
        if(state.routes[0].routeName === 'home'){

          store.dispatch(myFunction('home')) 

        } else if(state.routes[0].routeName === 'requests'){

          store.dispatch(myFunction('requests'))

        }
      }

      defaultHandler();
    }
  })
})