blog icon indicating copy to clipboard operation
blog copied to clipboard

react 禁止“事件冒泡”

Open youngwind opened this issue 9 years ago • 6 comments

标题的说法其实不太准确,因为react原生的事件系统本身就是事件代理的,意味着事件会一直冒泡到document进行绑定。所以,使用普通的**event.stopPropagation();**是没有办法在react中实现阻止事件“冒泡”类似的操作的。 stackoverflow和github issue上都有相关的讨论,比如

  1. http://stackoverflow.com/questions/24415631/reactjs-syntheticevent-stoppropagation-only-works-with-react-events
  2. https://github.com/facebook/react/search?q=stopPropagation&type=Issues&utf8=%E2%9C%93

最后我找到了一个比较简单地解决方法,就是 react-native-listener

// before use react-native-listener
<a style={hotSpotStyle} onClick={this.handleClick}></a>
// after use react-native-listener
<NativeListener key={index} onClick={this.handleClick}>
      <a style={hotSpotStyle}></a>
</NativeListener>

参考地址:https://www.npmjs.com/package/react-native-listener

youngwind avatar Dec 18 '15 15:12 youngwind

omg

Fan-zexu avatar Feb 06 '17 10:02 Fan-zexu

@simongfxu 是如何处理的呐?

Thinking80s avatar Feb 07 '17 10:02 Thinking80s

@Thinking80s 文章已过时,React现在已经没有这个问题了。

https://jsfiddle.net/alexander/69z2wepo/34253/

SiZapPaaiGwat avatar Feb 08 '17 02:02 SiZapPaaiGwat

大概是什么原理呢?

cqupt-yifanwu avatar Mar 06 '17 07:03 cqupt-yifanwu

我用的event.stopPropagation()是可以阻止事件冒泡的

Nick930826 avatar Nov 29 '17 07:11 Nick930826

给 Icon 加个样式 pointer-events: none 就能直接解决

qq34347476 avatar Apr 06 '22 03:04 qq34347476