youngwind / blog

梁少峰的个人博客
4.66k stars 384 forks source link

react 禁止“事件冒泡” #9

Open youngwind opened 8 years ago

youngwind commented 8 years ago

标题的说法其实不太准确,因为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

Fan-zexu commented 7 years ago

omg

Thinking80s commented 7 years ago

@simongfxu 是如何处理的呐?

SiZapPaaiGwat commented 7 years ago

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

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

cqupt-yifanwu commented 7 years ago

大概是什么原理呢?

Nick930826 commented 6 years ago

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

qq34347476 commented 2 years ago

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