微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Flatlist React 原生卡的 onPress 不会在 Android 上触发

如何解决Flatlist React 原生卡的 onPress 不会在 Android 上触发

我正在为我的应用使用 Expo我有一个水平平面列表,用于呈现我的数据 react native paper's 卡片。我看到 Card 有 onPress 功能。我用它来导航另一个页面。但是 onPress 功能不会在 Android 设备上触发。我知道 React Native 的可触摸不透明度在 Android 上存在定位问题。我尝试了 hitSlop 和内联样式 zIndex 但仍然不起作用。我也用 react-native's touchable-opacity 包裹我的卡片,玩定位仍然没有帮助我,只有当我使用 react-native-gesture-handler's touchable-opacity 时它才有效,但它在 IOS 上不起作用。希望任何人都可以帮助我...


import React from 'react';
import { Card } from 'react-native-paper';
import { useNavigation } from '@react-navigation/native';

interface Iprops {
  item: string;
}

export default function RenderCard({ item }: Iprops) {
  const navigation = useNavigation();
  return (
    <Card
      hitSlop={{ "bottom": 30,"top": 30,"right": 30,"left": 30 }}
      onPress={() => {
        navigation.navigate(`detail`,{ // THIS DOES NOT TRIGGER ON ANDROID 
          "id": `${item.pk}`
        });
      }}
      style={{ "marginBottom": 20 }}>
      <Card.Cover
        source={{ "uri": `${item.img_url}` }} />
      <Card.Actions>
        <Card.Title title={item.name} subtitle="Card Subtitle" />
      </Card.Actions>
    </Card>
  );
}

解决方法

如您所说,您应该为要在卡片上渲染的元素添加可触摸的不透明度。 TouchableOpacity 可能很棘手。所以,首先给它一个边框宽度:1 和边框颜色的样式来查看屏幕上实际的可触摸区域。然后您开始将它们与图标或图像或您正在渲染的任何内容结合在一起。 TouchableOpacity 有效,但定位可能很棘手。您必须了解它才能更好地使用它。将 touchableOpacity 视为带边框的视图,那么它会更容易掌握。另外,如果你不给 touchableOpacity 在样式中的绝对位置,它会在屏幕之外的某个地方,我永远无法把它带到我能看到的地方来定位它。因此您也可以添加 'position'

,

我放弃了基于平台的定位和渲染组件。

Platform.OS === `ios` ?
    <Card
      onPress={() => {
        navigation.navigate(`detail`,{
          "id": `${item.pk}`
        });
      }}
      style={{ "marginBottom": 20 }}>
      <Card.Cover source={{ "uri": `${item.img_url}` }} />
      <Card.Actions>
        <Card.Title title={item.name} subtitle="Card Subtitle" right={Beer} />
      </Card.Actions>
    </Card> :
    <TouchableOpacity
      onPress={() => {
        navigation.navigate(`detail`,{
          "id": `${item.pk}`
        });
      }}
    >
      <Card style={{ "marginBottom": 20 }}>
        <Card.Cover source={{ "uri": `${item.img_url}` }} />
        <Card.Actions>
          <Card.Title title={item.name} subtitle="Card Subtitle" right={Beer} />
        </Card.Actions>
      </Card>
    </TouchableOpacity>;

,

我注意到在绝对定位的平面列表中使用 onPressIn 或 onPressOut 确实适用于 Android,但 onPress 不起作用。我希望这可能对寻找答案的人有所帮助。

您需要使用 react-native-gesture-handler 中的 TouchableOpacity 元素。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。