【问题标题】:TouchableOpacity not clickable when above a MapView with backgroundColor在具有 backgroundColor 的 MapView 上方时,TouchableOpacity 不可点击
【发布时间】:2019-06-04 13:46:03
【问题描述】:

我在使用 TouchableOpacity 和 react-native-maps 时遇到问题。

我有一个带有 MapView 和一个 View 的 View,里面有一个绝对定位的 TouchableOpacity,如下面的代码:

<View style={{ flex: 1, flexDirection: 'column-reverse' }}>
  <MapView style={{ flex: 1 }} />
  <View style={{ height: 55 }}>
    <TouchableOpacity style={{ position: 'absolute', top: 100 }}>
      <Text>Button</Text>
    </TouchableOpacity>
  </View>
</View>

当我在这种情况下单击 TouchableOpacity 时,它按预期工作,但我需要我的内部视图具有白色背景色,如下所示:

<View style={{ flex: 1, flexDirection: 'column-reverse' }}>
  <MapView style={{ flex: 1 }} />
  <View style={{ height: 55, backgroundColor: '#ffffff' }}>
    <TouchableOpacity style={{ position: 'absolute', top: 100 }}>
      <Text>Button</Text>
    </TouchableOpacity>
  </View>
</View>

但是,一旦我将 backgroundColor 标签放入样式中,TouchableOpacity 就完全停止工作,并且 MapView 上方的所有点击实际上都被视为地图本身的点击。

有人知道如何解决这个问题吗?我确实需要在 View 中有一个背景,所以无法删除它。

【问题讨论】:

  • 您是否尝试过禁用View 上的pointerEvents 属性?当backgroundColor not transparent 时,它可能在到达TouchableOpacity 之前捕获/吞下事件。
  • 刚刚尝试过(我不知道 PointerEvents),但不幸的是它仍然不起作用。对我来说,目前的快速解决方案是将两个组件放在另一个视图中,并在这个外部视图中设置背景。

标签: react-native react-native-maps


【解决方案1】:

尝试将视图放在 TouchableOpacity 中。

<View style={{ flex: 1, flexDirection: 'column-reverse' }}>
  <MapView style={{ flex: 1 }} />
  <TouchableOpacity style={{ position: 'absolute', top: 100 }}>
      <View style={{ height: 55, backgroundColor: '#ffffff' }}>
          <Text>Button</Text>
      </View>
  </TouchableOpacity>
</View>

【讨论】:

  • 这对我不起作用,因为我需要视图中的各种按钮,但如果我只需要一个按钮,代码就可以工作。谢谢
  • 你找到解决办法了吗?
【解决方案2】:

为自己找到了解决方案。如果你导入 TouchableOpacity,不要这样做:

import { TouchableOpacity } from "react-native-gesture-handler";

而是这样做:

import {TouchableOpacity} from 'react-native';

之后,您只需将 TouchableOpacity 直接放在 MapView 下方,就像我在这里所做的那样:

         <View style={styles.container}>
            <MapView 
                style={styles.map}
                zoomEnabled = {true}
                maxZoomLevel={10}
                rotateEnabled={false}
                loadingEnabled={true}
                onPress={e => {
                    console.log(e.nativeEvent.coordinate);
                    handleMapPress(e.nativeEvent.coordinate);
                }}
            />
            <TouchableOpacity style={{position: "absolute", bottom: "90%", left:"5%"}}>
                <AntDesign name="caretleft" size={40} color="orange"/>     
            </TouchableOpacity>
        </View>

您还可以将多个组件放置在 MapView 上,只需确保将它们放置在 MapView 下方,但在您的主视图中,该主视图将所有内容都包裹起来。

如果您想定位覆盖 MapView 的项目,请使用以下道具:

style={{position: "absolute", bottom: "90%", left:"5%"}}

right、left、bottom、top 用于定位您的组件覆盖 MapView。我发现使用“%”定义非常适合此目的,因为它会根据设备显示的大小动态适应您的屏幕。

【讨论】:

    猜你喜欢
    • 2016-07-18
    • 2017-11-19
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    相关资源
    最近更新 更多