在选项卡更改时反应导航

React Navigation on tab change

在不使用 Redux 的情况下,如何使用 React Navigation 选项卡导航器检测选项卡更改?

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

export default () => <MyTabNav
    ref={(ref) => { this.nav = ref; }}
    onNavigationStateChange={(prevState, currentState) => {
        //call function on current view
    }}
/>;
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,这就是您可以存储有关当前路由的全局信息的方式,这样您既可以检测选项卡更改,也可以判断哪个选项卡现在处于活动状态。

react-native 问题对此进行了长时间的讨论 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

用法:

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

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

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

如果您打算使用 Window 属性,您可以在 React 中轻松地做到这一点。

检查 window 是否存在于 render 内部的 return 之前。

if (typeof window !== "undefined") {
window.addEventListener('visibilitychange, () => {
window.document.title = window.document.hidden;
console.log(document.hidden ? "Out" : "In");
this.props.doFunction();

}

如果您正在使用 react-navigation version 5, then you can add tab-press listener right in your tab screen definition, to do some pre-processing, as mentioned in docs

<Tab.Navigator>
    <Tab.Screen
        component={HomeScreen}
        name="HomeScreen"
        listeners={{
          tabPress: e => {
            if (userIsNotLoggedIn) {
              // Prevent default action
              e.preventDefault();
              navigation.navigate("LoginScreen");
            }
          },
        }}
      />
      <Tab.Screen
        ../>
</Tab.Navigator>

说明:当Home选项卡将在BottomBar中被点击时,如果用户未登录,HomeScreen将不会' t 打开,而是 LoginScreen 将打开(注意:LoginScreen 是导航名称,将在屏幕的某个位置注册)。但是,如果用户已登录,那么它将正常运行。