防止事件冒起dom树

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

我有如下卡片组件

<div
      onClick={e => {
        console.log("DEMAND CARD CLICKED");
        if (isSelectionActive) {
          setSelected();
        }
      }}
    >

      <DemandCardFooter
        demandId={id}
        totalBooked={totalBooked}
        totalDemand={totalDemand}
      />
    </div>

这是<DemandCardFooter/>的外观

<div className="vt-card-footer d-flex justify-content-between align-items-baseline px-3">
      <DemandSelector demandId={demandId} />
      <p className="lead font-weight-bold mb-0">
        <span className="text-success">{totalBooked}</span> / {totalDemand}{" "}
        <small className="text-muted font-weight-normal">Units.</small>
      </p>
    </div>

最后这就是<DemandSelector/>的样子

const DemandSelector = ({ demandId }) => {
  const [isChecked, setChecked] = useRowSelector({
    path: "demands",
    payload: { id: demandId }
  });
  return (
    <Checkbox
      checked={isChecked ? true : false}
      onClick={e => {
        console.log("CHECKBOX CLICKED");
        e.stopPropagation();
        e.nativeEvent.stopImmediatePropagation();
        setChecked();
      }}
    />
  );
};

我的问题是,当我单击复选框时,复选框的onClick和卡的onClick都被触发,有什么办法可以将回调限制到最低级别?

enter image description here

javascript reactjs event-handling dom-events event-bubbling
1个回答
0
投票

这与事件冒泡无关,问题与事件捕获阶段有关。

事件已停止,您不会在代码中使用e.stopPropagation();冒泡。但是在父事件中不会阻止事件捕获。

您可以通过在父事件中添加e.stopPropagation();来阻止它。

<div
      onClick={e => {
         e.stopPropagation();
        console.log("DEMAND CARD CLICKED");
        if (isSelectionActive) {
          setSelected();
        }
      }}
    >
      <DemandCardFooter
        demandId={id}
        totalBooked={totalBooked}
        totalDemand={totalDemand}
      />
    </div>
© www.soinside.com 2019 - 2024. All rights reserved.