简体   繁体   中英

OnClick on child div should not trigger parent div's onClick method for a particular child

Consider the following React component

export default function App() {
  return (
    <div className="App" onClick={() => console.log("on app div")}>
      <div className="first" onClick={() => console.log("first div")}>
        first
      </div>
      <div className="second" onClick={() => console.log("second div")}>
        second
      </div>
      <div className="third">third</div>
    </div>
  );

}

So, a click on child div's will currently trigger onClick methods of both parent and child div's. But for the first child I would like only child onClick method to be triggered. Is there a way to do this?

I've tried giving the child div a higher z-index value but it's still triggering both onClicks, here is the css I've tried

.App {
  font-family: sans-serif;
  text-align: center;
  position: relative;
}
.first,.second,.third {
  position: absolute;
  width: 100px;
  line-height: 100px;
  text-align: center;
}

.first {
  background: lightblue;
  position: absolute;
  z-index: 10;
}

.second {
  background: lightcoral;
  position: absolute;
  left: 200px;
}

.third {
  background: lawngreen;
  position: absolute;
  left: 100px;
}

Could anyone please tell if there is anything wrong with the css I've tried or any other method in order to achieve this.

you should use event.stopPropagation()

<div className="second" onClick={(event) =>
    event.stopPropagation()
    console.log("second div")
 }>
    second
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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