简体   繁体   English

如何在 React-js 中为捕获阶段注册事件处理程序?

[英]how to register an event handler for the capture phase in React-js?

By default event of element are in the bubbling phase.默认情况下,元素的事件处于bubbling阶段。 in javascript if we going to convert it to capture, we have the following way:在 javascript 中,如果我们要将其转换为捕获,我们有以下方法:

1- when the value of useCapture is set to true, the event uses the capturing propagation(in third argument): 1- 当 useCapture 的值设置为 true 时,事件使用捕获传播(在第三个参数中):

element.addEventListener(event, function, useCapture);

2- jQuery only uses event bubbling. 2- jQuery 只使用事件冒泡。

now my main question is that although we make the evnet inline <div onclick= {} /> , how to change bubbling phase to capturing in React?现在我的主要问题是,虽然我们使 evnet 内联<div onclick= {} /> ,但如何在 React 中将冒泡阶段更改为捕获?

This is quite straightforward.这很简单。

For event bubbling对于事件冒泡

<div onClick={() => { alert('Bubbling');}} >
This will result into event bubbling
</div>

For event capturing用于事件捕获

<div onClickCapture={() => { alert('Capturing');}} >
This will result into event capturing
</div>

You can also refer to the official docs here你也可以参考这里的官方文档

 useEffect(() => {
    const handler = (event) => {
      //  write event handling logic here
    };
    // this will detect all clicks events
    document.addEventListener("click", handler, true);
    return () => {
      document.removeEventListener("click", handler);
    };
    // if we had a dependency, cleanup would be called before rerendering
  }, []);

assume that you have a button element in jsx假设你在 jsx 中有一个按钮元素

 <Button
    onClick={handleClick}
  >
    Test Button
  </Button>

when a user clicks on this button, since add true option the registered event inside the useEffect , browser will look at the top parent element which is document and if it has a click handler registered it will call that first.当用户单击此按钮时,由于在useEffect中添加了true选项注册事件,浏览器将查看顶部父元素,即文档,如果它注册了点击处理程序,它将首先调用它。

I explained in details here: What is event bubbling and capturing?我在这里详细解释了: 什么是事件冒泡和捕获?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM