React Navigation on tab change

我的未来我决定 提交于 2019-12-21 04:21:16

问题


Without using Redux, how do I detect a tab change with a react navigation tab navigator?

I know I need to somehow use onNavigationStateChange but I can't figure out how to update the current view.

export default () => <MyTabNav
    ref={(ref) => { this.nav = ref; }}
    onNavigationStateChange={(prevState, currentState) => {
        //call function on current view
    }}
/>;

回答1:


export default () => <MyTabNav
    ref={(ref) => { this.nav = ref; }}
    onNavigationStateChange={(prevState, currentState) => {
       const getCurrentRouteName = (navigationState) => {
         if (!navigationState) return null;
         const route = navigationState.routes[navigationState.index];
         if (route.routes) return getCurrentRouteName(route);
         return route.routeName;
       };
    global.currentRoute = getCurrentRouteName(currentState);
  }}
/>;

If you don't want to use redux, this is how you can store global information about the current route, so you can both detect a tab change and also tell which tab is now active.




回答2:


Actually, you can add an special listener in your component

componentDidMount () {
    this.props.navigation.addListener('willFocus', (route) => { //tab changed });
} 



回答3:


There's some long discussions about this from react-native issue 314, 486, 1335, and finally we got a better built in way to handle this, after Sep 27, 2017, react-navigation version v1.0.0-beta.13:

New Features

Accept a tabBarOnPress param (#1335) - @cooperka

Usage:

const MyTabs = TabNavigator({
  ...
}, {
  tabBarComponent: TabBarBottom /* or TabBarTop */,
  tabBarPosition: 'bottom' /* or 'top' */,
  navigationOptions: ({ navigation }) => ({
    tabBarOnPress: (scene, jumpToIndex) => {
      console.log('onPress:', scene.route);
      jumpToIndex(scene.index);
    },
  }),
});



回答4:


componentDidMount () {
    this.props.navigation.addListener('willFocus', (route) => { console.log(" Tab click is working ") });
} 


来源:https://stackoverflow.com/questions/44000640/react-navigation-on-tab-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!