admin管理员组

文章数量:1277888

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.

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.

Share Improve this question edited Jan 17, 2019 at 14:27 Johan Jönsson asked Jan 17, 2019 at 14:23 Johan JönssonJohan Jönsson 5693 gold badges12 silver badges24 bronze badges 3
  • there is a typo in the 2nd line: <div <span> – Beniamin H Commented Jan 17, 2019 at 14:25
  • you can use event.stopPropagation() – Sahil Raj Thapa Commented Jan 17, 2019 at 14:26
  • @BeniaminH oh yeha sorry edited happend when pasting it in only – Johan Jönsson Commented Jan 17, 2019 at 14:27
Add a ment  | 

2 Answers 2

Reset to default 8

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>

本文标签: javascriptReactjs onClick on both the Parent div and Child div Parent always firesStack Overflow