更改制表符时的导航

问题描述 投票:8回答:4

[不使用Redux,如何使用反应导航选项卡导航器检测选项卡更改?

我知道我需要以某种方式使用onNavigationStateChange,但我不知道如何更新当前视图。

export default () => <MyTabNav
    ref={(ref) => { this.nav = ref; }}
    onNavigationStateChange={(prevState, currentState) => {
        //call function on current view
    }}
/>;
react-native react-navigation
4个回答
5
投票
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);
  }}
/>;

如果您不想使用redux,可以通过这种方式存储有关当前路线的全局信息,这样既可以检测到选项卡更改,也可以知道哪个选项卡现在处于活动状态。


30
投票

实际上,您可以在组件中添加特殊的侦听器

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

3
投票

[react-native问题3144861335对此进行了长时间的讨论,最后,我们有了更好的构建方式来处理此问题,在2017年9月27日之后,是反应导航版本[C0 ]:

新功能

[接受tabBarOnPress参数(#1335)-@cooperka

用法:

v1.0.0-beta.13

0
投票
const MyTabs = TabNavigator({
  ...
}, {
  tabBarComponent: TabBarBottom /* or TabBarTop */,
  tabBarPosition: 'bottom' /* or 'top' */,
  navigationOptions: ({ navigation }) => ({
    tabBarOnPress: (scene, jumpToIndex) => {
      console.log('onPress:', scene.route);
      jumpToIndex(scene.index);
    },
  }),
});
© www.soinside.com 2019 - 2024. All rights reserved.