【问题标题】:React check if the event is bubbled/captured without using Ref反应检查事件是否在不使用 Ref 的情况下冒泡/捕获
【发布时间】:2020-07-23 08:43:13
【问题描述】:

这是使用 refs 的解决方案

import React, { useState, useRef } from "react";

function Bar() {
    const ref = useRef();
    return (
            <div
               ref={ref}
               onClick={(ev) => {
                  if (ev.target == ref.current) console.log("Target hit");
                }}
             >
              Click me, maybe <div>test</div>
            </div>
     );
}

在上面的解决方案中,当我们点击测试时,目标没有命中。我们可以吗 不使用 refs

获得相同的输出

【问题讨论】:

    标签: reactjs react-hooks react-ref


    【解决方案1】:

    使用事件的currentTarget 属性,它将始终引用它注册的元素,而不是触发它的元素target

    function Bar() {
        return (
                <div
                   onClick={(ev) => {
                      if (ev.target === ev.currentTarget) console.log("Target hit");
                    }}
                 >
                  Click me, maybe <div>test</div>
                </div>
         );
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      相关资源
      最近更新 更多