如何防止对话框消失? Reactjs

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

在此代码中,我显示带有按钮的弹出窗口,当单击负责取消的按钮时,会显示确认对话框。我希望弹出窗口在其外部单击时消失,所以我像这样处理它:

  const popupRef = useRef<HTMLDivElement>(null);

  const handleClickOutside = (event: MouseEvent) => {
    if (
      popupRef.current &&
      !popupRef.current.contains(event.target as Node)
    ) {
      onClose();
    }
  };
  

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

onClose
是关闭弹出窗口的回调。现在,当单击按钮时,我将创建如下对话框:

      {showCancelConfirmationDialog && 
      <CancelConfirmationDialog 
      onCancel={handleCloseDialog} 
      onConfirm={handleCancelReservation} 
      name={block.lessonWith} 
      time={chosenTime} 
      date={block.day} />}

  const handleCloseDialog = () => {
    console.log("closing");
    setShowCancelConfirmationDialog(false);
  }

  const handleCancelReservation = () => {
    console.log("block")
    block.isReserved = false;
    block.reservedBy = "notMe";
    onClose();
  }

对话框代码:

interface DeleteConfirmationDialogProps {
  onCancel: () => void;
  onConfirm: () => void;
  name: string;
}

const DeleteConfirmationDialog: React.FC<DeleteConfirmationDialogProps> = ({ onCancel, onConfirm, name }) => {
  return (
    <div className="delete-confirmation-dialog">
      <p className='delete-confirmation-dialog-p'>Te jazdy są zarezerwowane przez: {name} </p>
      <p className='delete-confirmation-dialog-p'>Czy na pewno chcesz je przesunąć i powiadomić o tym kursanta?</p>
      <button className='delete-confirmation-dialog-button' onClick={onConfirm}>Usuń i powiadom</button>
      <button className='delete-confirmation-dialog-button' onClick={onCancel}>Anuluj</button>
    </div>
  );
}

export default DeleteConfirmationDialog;

现在的问题是,无论我点击哪里,所有内容都会消失,因为

useEffect
handleClickOutside
无论如何都会被触发,而且我不知道发生了什么。如果我注释掉这段代码,它就可以正常工作。我尝试为对话框添加另一个
popupRef
但它不起作用。我还尝试在对话框处于活动状态时通过布尔值来控制它,但它也不起作用。

reactjs typescript react-hooks popup
2个回答
0
投票

也许最好的选择是使用现成的组件,例如 Material-UI 的

Dialog

您可以在此处找到更多带有良好示例的信息。


0
投票

我已经检查了你上面的代码。

我认为这方面存在一些问题

  const handleClickOutside = (event: MouseEvent) => {
    if (
      popupRef.current &&
      !popupRef.current.contains(event.target as Node)
    ) {
      onClose();
    }
  };

这是我的新代码。

const handleClickOutside = (event: MouseEvent) => {
  if (
     !popupRef.current ||
     popupRef.current.contains(event.target as Node)
   ) {
    return;
  }
  onClose();
};

您还需要触发

touchstart
事件来关闭模态框。

document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('touchstart', handleClickOutside);

document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('touchstart', handleClickOutside);

如果您还有任何问题,请告诉我。
我希望我的代码对您有用。
谢谢你。

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