[英]How can I get my 'click' event handler to reference these specific elements?
Here's a sandbox of a problem I've run into.这是我遇到的一个问题的沙箱。 I'm using React:
我正在使用反应:
<div className="1" onClick={onClickHandler}>
<div className="2">
<img className="3">
</div>
</div>
In scenarioA, img
wasn't present & onClickHandler
's e.target
referenced element 2
.在场景 A 中,
img
不存在onClickHandler
的e.target
引用了元素2
。 I believe this is because:我相信这是因为:
e.currentTarget
, e.target
will reference the 'highest' element you click on that has a 'click' handler - with an exception: if the element has a descendant that is also clicked on when you click, it'll reference the lowest descendant.e.currentTarget
一样, e.target
将引用您点击的具有“点击”处理程序的“最高”元素——有一个例外:如果该元素有一个在您点击时也被点击的后代,它将引用最低的后代。 The problem: in scenarioB, img
has been added & now e.target
refers to img
.问题:在场景 B 中,添加了
img
并且现在e.target
指的是img
。 I need to refer to element 1
& 2
and intend to do this with the event handler staying on '1'.我需要参考元素
1
和2
,并打算在事件处理程序保持在“1”的情况下执行此操作。
Solutions:解决方案:
Somehow, in onClickHandler
get it to see '2'.不知何故,在
onClickHandler
中让它看到“2”。
Refactor img
to be like '2'.将
img
重构为“2”。 In my project, I think all this'd involve is making img
have all the html attributes '2' has.在我的项目中,我认为所有这一切都涉及使
img
具有“2”具有的所有 html 属性。 However, I know having the attributes on '2' works - and even though I can't think of a way why this solution would break, I'm hesitant - especially if solution#1 works.但是,我知道“2”上的属性有效——尽管我想不出为什么这个解决方案会失败,但我很犹豫——尤其是如果解决方案#1 有效。
Summarizing the Question and Solution总结问题和解决方案
Below you can see two onClickHandler that logs out the event.target.您可以在下面看到两个注销 event.target 的 onClickHandler。
Expected : retrieve the parent node of the leaf nodes (children nodes without children nodes or innermost HTML element).预期:检索叶节点的父节点(没有子节点的子节点或最里面的 HTML 元素)。
Actual : retrieved the leaf nodes.实际:检索叶节点。
Fix : change event.target
to event.target.parentNode
.修复:将
event.target
更改为event.target.parentNode
。
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
function onClickHandler(event) {
console.log(event.target); // THE FIX: change this to event.target.parentNode
}
return (
<>
<div className="one" onClick={onClickHandler}>
<div className="two"></div>
</div>
<div className="one" onClick={onClickHandler}>
<div className="two">
<img className="three" />
</div>
</div>
</>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.