如何为父 div 添加 onClick 并且不让其子级继承它?

我正在为我的 Web 应用程序使用下一个 js,我正在尝试为其中包含 mor 元素的 div 设置 onclick。我不希望其他子元素调用 onclick 函数,因为我只希望后台 div 执行该函数,但是当我向父级添加 onlclick 函数时。

我如何做到这一点??这是我的参考代码:

<div onClick={()=>{
  /* trigger something */
}}>
  /* these should not trigger the above onlick */
  <div class="css-bg">
    <button></button>
  </div>
  <text>Some Sample Text</text>
</div>

hufengguang 回答:如何为父 div 添加 onClick 并且不让其子级继承它?

我不知道这是否是你想要的,但如果你想要的只是一个可点击的背景 div,上面有不激活背景的 onClick 事件的组件,那么你可以分离背景div 从它的孩子,例如:

import "./styles.css";

export default function App() {
  return (
    <div className="parent-div">
      <div
        className="div-style"
        onClick={() => console.log("go to tweet page")}
      ></div>
      <a href="#tweet-author">
        <img
          className="img-style"
          src="https://www.pixsy.com/wp-content/uploads/2021/04/ben-sweet-2LowviVHZ-E-unsplash-1.jpeg"
          onClick={() => console.log("go to tweet author")}
          alt="Author"
        />
      </a>
      <h2 className="h2-style">Start editing to see some magic happen!</h2>
    </div>
  );
}

您可以为 div 背景添加样式,使其覆盖整个容器(或调整样式以符合您的偏好,添加相对于其他元素的显示以使其可见:

body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.parent-div {
  position: relative;
  height: 200px;
  padding: 15px;
  margin: 15px;
}

.div-style {
  background: url("https://i.pinimg.com/originals/0b/1b/04/0b1b0434864a51a9e607c6241c148090.jpg");
  background-size: cover;
  background-position: center;
  position: absolute;
  border-radius: 7px;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.img-style {
  position: relative;
  height: 50px;
  width: 50px;
  border-radius: 50%;
}

.h2-style {
  position: relative;
}

让我知道这是否是您想要的,如果不是,请添加评论,以便我可以相应地调整我的答案。

,

我相信这是不可能的,因为父级有一个点击事件,子级通常也会有它。一种方法是使用 pointer-events 禁用对子项的点击,但即使不是那样,也只能在父项上。

,

您需要使用 Event.stopPropagation()。 Event 接口的此方法可防止当前事件在捕获和冒泡阶段进一步传播。阅读here

<button onClick={(e) => e.stopPropagation()}>Button</button>

这将防止在您单击子项(按钮)时触发父项的 onclick 侦听器。

本文链接:https://www.f2er.com/988.html

大家都在问