Javascript React.js 中的冒泡和捕获示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34522931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:29:42  来源:igfitidea点击:

Example for Bubbling and Capturing in React.js

javascriptreactjsevent-bubblingevent-capturing

提问by Socrates

I am looking for an example in handling Bubbling and Capturing in React.js. I found one with JavaScript, but I am having trouble finding the equivalent for React.js.

我正在寻找在 React.js 中处理冒泡和捕获的示例。我找到了一个 JavaScript,但我找不到 React.js 的等效项。

How would I have to create an example for Bubbling and Capturing in React.js?

我必须如何为 React.js 中的冒泡和捕获创建示例?

回答by Michelle Tilley

Bubbling and capturing are both supported by React in the same way as described by the DOM spec, except for how you go about attaching handlers.

React 以与 DOM 规范描述的相同方式支持冒泡和捕获,除了您如何附加处理程序。

Bubbling is as straightforward as with the normal DOM API; simply attach a handler to an eventual parent of an element, and any events triggered on that element will bubble to the parent as long as it's not stopped via stopPropagationalong the way:

冒泡和普通的 DOM API 一样简单;只需将处理程序附加到元素的最终父元素,只要它没有在此过程中停止,在该元素上触发的任何事件都会冒泡到父元素stopPropagation

<div onClick={this.handleClick}>
  <button>Click me, and my parent's `onClick` will fire!</button>
</div>

Capturing is just as straightforward, though it's mentioned only briefly in the docs. Simply add Captureto the event handler property name:

捕获同样简单,尽管在 docs 中只简要提到了它。只需添加Capture到事件处理程序属性名称:

<div onClickCapture={this.handleClickViaCapturing}>
  <button onClick={this.handleClick}>
    Click me, and my parent's `onClickCapture` will fire *first*!
  </button>
</div>

In this case, if handleClickViaCapturingcalls stopPropagationon the event, the button's onClickhandler will not be called.

在这种情况下,如果handleClickViaCapturing调用stopPropagation该事件,onClick则不会调用按钮的处理程序。

This JSBinshould demonstrate how capturing, bubbling, and stopPropagationworks in React: https://jsbin.com/hilome/edit?js,output

这个 JSBin应该演示如何stopPropagation在 React 中捕获、冒泡和工作:https: //jsbin.com/hilome/edit?js,output