离开屏幕回调 React Navigation Tab Navigator

Leave screen callback React Navigation Tab Navigator

我有一个像这样的 React 导航选项卡组件:

const RootNavigator=TabNavigator({
Home:{
    screen: Home
    ,navigationOptions:{
        tabBarIcon: ({focused}) => (
            <Icon
                name={focused?'ios-home':'ios-home-outline'}
                style={{color:'#464646'}}
                size={16}
            />
        )
    }
},
Notifications:{
    screen: Notifications
    ,navigationOptions:{
        tabBarIcon: ({focused}) => (
            <TabNotifications focused={focused} />
        )
    }
},{});

有没有办法在离开屏幕时进行回调?

在这种情况下,我想在将通知 tab.Such 标记为已看到通知并删除徽章指示器时执行一项功能。

截至目前,我正在从另一个组件中拉出通知图标以显示数字徽章。

提前致谢。

一种选择是使用onNavigationStateChange检查导航的当前变化并执行清除通知等所需的操作

onNavigationStateChange(prevState, newState, action)

Function that gets called every time navigation state managed by the navigator changes. It receives the previous state, the new state of the navigation and the action that issued state change. By default it prints state changes to the console.

另一种选择是使用 addListener。这样您就可以订阅 willFocus/didFocuswillBlur/didBlur 事件并执行您需要的操作。

addListener - Subscribe to updates to navigation lifecycle

React Navigation emits events to screen components that subscribe to them:

  • willBlur - the screen will be unfocused
  • willFocus - the screen will focus
  • didFocus - the screen focused (if there was a transition, the transition completed)
  • didBlur - the screen unfocused (if there was a transition, the transition completed)

来自文档的示例

const didBlurSubscription = this.props.navigation.addListener(
  'didBlur',
  payload => {
    console.debug('didBlur', payload);
  }
);
// Remove the listener when you are done
didBlurSubscription.remove();

// Payload
{
  action: { type: 'Navigation/COMPLETE_TRANSITION', key: 'StackRouterRoot' },
  context: 'id-1518521010538-2:Navigation/COMPLETE_TRANSITION_Root',
  lastState: undefined,
  state: undefined,
  type: 'didBlur',
};

对于那些想要第三种选择的人,您可以使用 docs 建议的 NavigationEvents 组件来收听导航挂钩以及您打算做的任何事情。

Edit: This is documentation for React Navigation 2.x, which is no longer actively maintained. For up-to-date documentation, see the latest version (6.x).

import React from 'react';
import { View } from 'react-native';
import { NavigationEvents } from 'react-navigation';

const MyScreen = () => (
  <View>
    <NavigationEvents
      onWillFocus={payload => console.log('will focus',payload)}
      onDidFocus={payload => console.log('did focus',payload)}
      onWillBlur={payload => console.log('will blur',payload)}
      onDidBlur={payload => console.log('did blur',payload)}
    />
    {/* 
      Your view code
    */}
  </View>
);

export default MyScreen;