React Navigation v.5 选项卡栏图标导航到模态

React Navigation v.5 Tab Bar Icon Navigate to Modal

有人知道 react navigation v.5 中 tabBarOnPress 的替代品吗?我想在用户按下 tabIcon 时导航到模式堆栈(即取消其默认导航行为),但图标似乎首先导航到选项卡屏幕,然后导航到模式。

为了澄清,这是我的 PostIcon TabIcon 组件

export const PostStackIcon: React.FC<TabBarIconProps> = ({ size, color }) => {
    const navigation = useNavigation();

    const goToCreatePost = () => {
        navigation.navigate('CreatePostStack', { screen: 'CreatePost'});
    }

    return (
        <TouchableWithoutFeedback onPress={() => goToCreatePost()}>
            <Icon
                name="Post"
                width={size * 2}
                height={size}
                fillOpacity={0}
                stroke={color} 
                secondaryStroke={color}
            />
        </TouchableWithoutFeedback>
    )
}

Official document

您可以使用 Tab.Screenlisteners 道具,这是最接近 tabBarOnPress 恕我直言的替代方法。

以下引用自文献:

Sometimes you might want to add a listener from the component where you defined the navigator rather than inside the screen. You can use the listeners prop on the Screen component to add listeners. The listeners prop takes an object with the event names as keys and the listener callbacks as values.

示例:

<Tabs.Screen
  name="Chat"
  component={Chat}
  listeners={{
    tabPress: e => {
      // Prevent default action
      e.preventDefault();
    },
  }}
/>

You can also pass a callback which returns the object with listeners. It'll receive navigation and route as the arguments.

示例:

<Tabs.Screen
  name="Chat"
  component={Chat}
  listeners={({ navigation, route }) => ({
    tabPress: e => {
      // Prevent default action
      e.preventDefault();

      // Do something with the `navigation` object
      navigation.navigate('AnotherPlace');
    },
  })}
/>