简体   繁体   English

反应事件冒泡/传播

[英]React event bubling / propagation

I have a simple component like:我有一个简单的组件,例如:

<div onClick={toggleHiden} className="faq-item-header">
 <h3>What is Bookmark?</h3>
 <img src={iconArrow} alt="arrow" />
</div>

在此处输入图像描述

This is the onclick function, I just want to toggle classlist.这是onclick功能,我只想切换classlist。

const toggleHiden = (e) => {
    console.log(e.target);
    e.target.nextSibling.firstChild.classList.toggle("hidden");
  };

My plan is to run toggleHiden function on div click, but when my mouse click above img or h3 the e.target is changing, I try to add stopPropagation into the h3:我的计划是在 div 点击时运行toggleHiden函数,但是当我的鼠标点击imgh3上方时, e.target正在改变,我尝试将stopPropagation添加到 h3 中:

<h3 onClick={(e) => e.stopPropagation()}>What is Bookmark?</h3>

and now the h3 cannot be clicked.现在无法单击 h3。

What I want is whether I click on the img or h3 it still count as click on the parent div我想要的是无论我点击img还是h3它仍然算作点击父div

How I can overcome this?我怎样才能克服这个?

You need to use event.srcElement instead of event.target , as target is the deepest element you clicked, it may be not the same element you bind the click event with, it can be one of it's children.您需要使用event.srcElement而不是event.target ,因为target是您单击的最深元素,它可能与您绑定 click 事件的元素不同,它可以是它的子元素之一。

Or you can covert you click handler function to a declaration function and use this instead.或者您可以将单击处理程序函数转换为declaration function并改用this

If you are using this approach then you can do following:如果您使用这种方法,那么您可以执行以下操作:

if(e.target.tagName === "h3" || e.target.tagName === "img") {             
   e.target.parent.nextSibling.firstChild.classList.toggle("hidden");
}
else {
  e.target.nextSibling.firstChild.classList.toggle("hidden");
}

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

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