繁体   English   中英

单击子项时停止父onClick(React或vanilla JS)

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

我有一个粘性条,我想通过在右侧使用position: absolute的X来让用户关闭。 但是,点击它时,它也会触发“分享到Facebook”事件。 我如何阻止这种情况发生?

在此输入图像描述

JS档案

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文件(这是一个sass文件所以没有分号和东西

.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将像你编写的那样工作,但点击事件的事件处理程序被称为onClick ,而不是handleClick

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

将共享包含到跨越的Facebook文本中,并将onClick处理程序附加到该文本。

您不应该使用onClick将带有onClick的元素嵌套在另一个元素中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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