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

ain*_*est 13 react-native

当我长按图像时,我有一个带有图像网格的滚动视图我想停止将鼠标事件传播到滚动视图,只是监视动作.意图在压出时重新初始化传播.谁知道怎么样?

小智 17

将以下内容添加到以<View>捕获传播的事件并停止它:

  • 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>
Run Code Online (Sandbox Code Playgroud)


pst*_*ton 7

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

<TouchableOpacity onPress={this.onPressOuter}>
    <TouchableOpacity activeOpacity={1}>
        <Text>Content</Text>
    </TouchableOpacity>
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)

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

  • 如果您有任何&lt;View&gt;子元素,则此方法无效,例如:`&lt;&lt; TouchableOpacity onPress = {this.onPressOuter}&gt; &lt;TouchableOpacity activeOpacity = {1}&gt; &lt;Text&gt; Content &lt;/ Text&gt; &lt;View&gt; // this.onPressOuter在这里称为&lt;/ View&gt; &lt;/ TouchableOpacity&gt; &lt;/ TouchableOpacity&gt;` (2认同)

Jar*_*iuk 1

您应该看一下手势响应器的方法:https://facebook.github.io/react-native/docs/gesture-responder-system.html#responder-lifecycle。实际上,更简单的方法是看一下 PanResponder https://facebook.github.io/react-native/docs/panresponder.html - 首先查看 UIExplorer 示例以了解它的运行情况: https://github。 com/facebook/react-native/blob/master/Examples/UIExplorer/ResponderExample.js。我不确定这是否能处理您的长按情况?

  • @jarek 示例链接已损坏 (4认同)
  • 只需将属性 `onStartShouldSetResponder={event =&gt; true}` 添加到您想要防止冒泡的 &lt;View&gt; 中即可。 (3认同)