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

问题描述 投票:1回答:2

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

enter image description here

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
    ...
javascript html css reactjs
2个回答
1
投票

stopPropagation会像你写的那样工作,但点击事件的事件处理程序叫做onClick,而不是handleClick

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

1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.