在不使用 Ref 的情况下反应检查事件是否为 bubbled/captured
React check if the event is bubbled/captured without using Ref
这是使用 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>
);
}
In the above solution, target is not hit when we click on test. Can we
get the same output without using refs
使用事件的 currentTarget
属性,它将始终引用它注册的元素,而不是触发它的元素 target
:
function Bar() {
return (
<div
onClick={(ev) => {
if (ev.target === ev.currentTarget) console.log("Target hit");
}}
>
Click me, maybe <div>test</div>
</div>
);
}
这是使用 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>
);
}
In the above solution, target is not hit when we click on test. Can we get the same output without using refs
使用事件的 currentTarget
属性,它将始终引用它注册的元素,而不是触发它的元素 target
:
function Bar() {
return (
<div
onClick={(ev) => {
if (ev.target === ev.currentTarget) console.log("Target hit");
}}
>
Click me, maybe <div>test</div>
</div>
);
}