如何停止 React-Native 中的触摸事件传播

How to stop touch event propagation in React-Native

当我长按图像时,我有一个带有图像网格的滚动视图我想停止将鼠标事件传播到滚动视图并只监视移动。目的是在按下时重新初始化传播。有人知道怎么做吗?

您应该看看手势响应程序的方法:https://facebook.github.io/react-native/docs/gesture-responder-system.html#responder-lifecycle . Actually even simpler way will be to take a look at the PanResponder https://facebook.github.io/react-native/docs/panresponder.html - first see the UIExplorer example to see it in operation: https://github.com/facebook/react-native/blob/master/Examples/UIExplorer/ResponderExample.js。我不确定这是否会处理您的长按情况?

我通过使用将内部变量设置为 true 的 class 方法包装我的新闻事件解决了这个问题,然后执行原始逻辑,完成后,再次将内部变量设置为 false。然后,您可以包装容器组件事件处理程序以检查内部变量是设置为 true 还是 false。 例如:

<TouchableOpacity onPress={this.doSomething1}>
    <TouchableOpacity onPress={this.doSomething2}>
        <Image ... />
    </TouchableOpacity>
</TouchableOpacity>

doSomething1() {
    this.preventDefault = true;
    doSomeLogic();
    this.preventDefault = false;
}

doSomething2() {
    if(!this.preventDefault) {

    }
}

这可能是自以前的答案以来的新内容,但我发现您可以使用另一个“可触摸”来吞噬事件:

<TouchableOpacity onPress={this.onPressOuter}>
    <TouchableOpacity activeOpacity={1}>
        <Text>Content</Text>
    </TouchableOpacity>
</TouchableOpacity>

在此示例中,触摸文本不会触发 onPressOuter

在我的例子中,外部可触摸的 onPress 首先被调用,即使我按下了内部可触摸。

我所做的是使用内部可触摸的 onPressInonPressOut 来确定用户按下的是内部还是外部可触摸 - 通过在组件中设置标志 class,在 onPressIn 上清除它,然后在 onPressOut 上清除它,然后在外部可触摸的 onPress 处理程序中检查该标志,如果已设置则退出。

这将是最简单的答案:

在您希望停止传播的点的内部视图上使用它

onTouchEnd={(e) => {
   e.stopPropagation()
}}

添加到视图以捕获传播的事件并停止它

  • onStartShouldSetResponder={(event) => true}
  • onTouchEnd={(e) => { e.stopPropagation(); }}
<TouchableOpacity onPress={this.doSomething1}>
  <View
   onStartShouldSetResponder={(event) => true}
   onTouchEnd={(e) => {
     e.stopPropagation();
   }}
  >
      <TouchableOpacity onPress={this.doSomething2}>
        <Image ... />
      </TouchableOpacity>
  </View>
</TouchableOpacity>