TabNavigator中图标的onpress事件(通过react-navigation进行本机反应)

时间:2019-05-04 22:17:10

标签: reactjs react-native

我的标签导航器中包含一个图标,如下所示:

const SearchTabBarIcon = ({ tintColor }) => (
      <IconMCI
        name="account-search"
        size={45}
        color={tintColor}
        onPress={() => console.log('HELP!!')}
      />
    );

...。然后我的tabNavigator看起来像这样:

const SignedInTabNav = TabNavigator(
  {
    Profile: {
      screen: Profile,
      navigationOptions: {
        tabBarLabel: 'Me',
        tabBarIcon: ProfileTabBarIcon,
      },
    },
    Search: {
      screen: Search,
      navigationOptions: {
        tabBarLabel: 'Search',
        tabBarIcon: SearchTabBarIcon,
      },
    },

    tabBarComponent: TabBarBottom,
    animationEnabled: false,
  }, 
);

当我单击图标时会触发console.log,但是tabNavigator的本机功能丢失了。 我该如何触发onPress事件,但又要保持导航功能?

我听说我应该“ 将导航的道具添加到渲染器中的组件 ”。 App.js的呈现功能如下所示:

 render() {
    const Layout = createRootNavigator(this.props.isAuthenticated);

    return (
      <View style={{ flex: 1, backgroundColor: '#F8F8FF' }}>
        <Layout />
      </View>
    );
  }

...。函数createRootNavigator看起来像这样

  const createRootNavigator = (authenticated = false) =>
      createSwitchNavigator(
        {
          SignedInTabNav: {
            screen: SignedInTabNav,
          },
          SignedOutStackNav: {
            screen: SignedOutStackNav,
          },
        },
        {

          initialRouteName: authenticated ? 'SignedInTabNav' : 'SignedOutStackNav',
        },
      );

.. so,那么在哪里/如何在App.js的渲染器中添加导航道具?...并将其通过createRootNavigator .....以及进一步通过createSwitchNavigator ....传递给最终传递到SignedInTabNav(TabNavigator)中,其中引用了搜索图标?

2 个答案:

答案 0 :(得分:0)

您可以简单地使用 tabBarOnPress 回调作为其他选项来处理新闻事件,例如:

const SignedInTabNav = TabNavigator(
  {
    Profile: {
      screen: Profile,
      navigationOptions: {
        tabBarLabel: 'Me',
        tabBarIcon: ProfileTabBarIcon,
      },
    },
    Search: {
      screen: Search,
      navigationOptions: {
        tabBarLabel: 'Search',
        tabBarIcon: SearchTabBarIcon,
        tabBarOnPress: ({ navigation, defaultHandler }) => {
          console.log('this will be fired just before nagivation happens')
          defaultHandler() // if you omit this, navigation will not happen
        }
      },
    },

    tabBarComponent: TabBarBottom,
    animationEnabled: false,
  }, 
);

答案 1 :(得分:0)

解决方案是使用reactNavigation中的'didFocus'事件

https://reactnavigation.org/docs/en/function-after-focusing-screen.html

  componentDidMount() {
    const { navigation } = this.props;
    this.focusListener = navigation.addListener('didFocus', () => {
      // The screen is focused
      // Call any action
    });
  }