React.js 中的冒泡和捕获示例 [英] Example for Bubbling and Capturing in React.js

查看:41
本文介绍了React.js 中的冒泡和捕获示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

解决方案

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

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

<button>点击我,我父母的`onClick`就会触发!</button>

捕获同样简单,尽管 仅在文档中简要提及.只需将 Capture 添加到事件处理程序属性名称.例如 onClick 变成 onClickCapture:

<button onClick={this.handleClick}>单击我,我父母的 `onClickCapture` 将*先*触发!

在这种情况下,如果 handleClickViaCapturing 对事件调用 stopPropagation,按钮的 onClick 处理程序将不会被调用.

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

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.

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

解决方案

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.

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 stopPropagation along the way:

<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 Capture to the event handler property name. For example onClick becomes onClickCapture:

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

In this case, if handleClickViaCapturing calls stopPropagation on the event, the button's onClick handler will not be called.

This JSBin should demonstrate how capturing, bubbling, and stopPropagation works in React: https://jsbin.com/hilome/edit?js,output

这篇关于React.js 中的冒泡和捕获示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆