简体   繁体   中英

stop parent onClick when child is clicked (React or vanilla JS)

I have a sticky bar that I would like to let users close out by having an X in the right side with position: absolute . However, when clicked, it also fires off the "Share to Facebook" event. How do I stop this from happening?

在此输入图像描述

JS File

return (
    <div
      className={'ShareBar'}
      onClick={()=>console.log('sharing')}>
        <span className={'ShareCTA'}>
          {facebook.svg} Share on Facebook &trade;
          <span
            className={'CloseButton'}
            handleClick={function (e) { e.stopPropagation()/*attempted fix*/; console.log('closing'); return; }}>
              X
          </span>
        </span>
    </div>
  );

CSS File (it's a sass file so no semicolons and stuff

.ShareBar
  position fixed
  bottom 0
  z-index 9999
  display flex
  justify-content flex-end
  align-items center
  height 48px
  cursor pointer
  width 100%
  ...

  .ShareCTA
    width 100%
    position relative
    display flex
    justify-content center
    align-items center
    font-size 20px
    ...
    svg
      height 20px

  .CloseButton
    position absolute
    z-index 99999
    right 10px
    border-radius 50%
    height 40px
    width 40px
    display flex
    justify-content center
    align-items center
    ...

stopPropagation will work like you have written, but the event handler for click events is called onClick , not handleClick :

<span
  className={'CloseButton'}
  onClick={e => e.stopPropagation()}
>
  X
</span>

Wrap the Share to Facebook text in a span and attach the onClick handler to that.

You shouldn't nest an element with an onClick inside another with an onClick.

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