Example for Bubbling and Capturing in React.js

六月ゝ 毕业季﹏ 提交于 2019-11-26 09:36:34

问题


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?


回答1:


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:

<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



来源:https://stackoverflow.com/questions/34522931/example-for-bubbling-and-capturing-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!