首页 > 解决方案 > 如何为父 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>

标签: javascripthtmlcssreactjs

解决方案


我不知道这是否是您想要的,但如果您想要的只是一个可点击的背景 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;
}

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


推荐阅读