简体   繁体   中英

React/js onClick on both the Parent div and Child div. Parent always fires

Hello i got a problem with having onClick on my parent and on its child that triggers which menuSection shows up. And even if i click on the child its the parents section that shows up. How to only trigger the child if that element gets clicked?

    <div> onClick={() => props.onClick(MenuSection.Default)} >
          <div <span><InfoIcon /></span> Some info</div>
          <div>More Info</div>
          <div>Even more Info</div>
          <div onClick={() => props.onClick(MenuSection.NotDefault)}><InfoIcon /></div>
    </div>

So here is how it looks and its always MenuSection.Default that shows up never MenuSection.NotDefault.

pass in e in the function and use

e.stopPropagation();

<div onClick={() => props.onClick(MenuSection.Default)} >
      <div <span><InfoIcon /></span> Some info</div>
      <div>More Info</div>
      <div>Even more Info</div>
      <div onClick={(e) => e.stopPropagation();props.onClick(MenuSection.NotDefault)}><InfoIcon /></div>
</div>

But I would also move the onClick inline function out of the render method and reference it with "this.nameOfClickMethod", nameOfClickMethod is of course to be named at your choise.

You can use event.stopPropagation() . It prevents the event from propagating.

<div> onClick={() => { props.onClick(MenuSection.Default)} } >
          <div <span><InfoIcon /></span> Some info</div>
          <div>More Info</div>
          <div>Even more Info</div>
          <div onClick={(e) => { e.stopPropagation();props.onClick(MenuSection.NotDefault)}}><InfoIcon /></div>
    </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