我使用contains
来确定是否在模式窗口之外发生了单击,并基于此关闭模式窗口.
问题如下:即使表单判断isFormNotEmpty
的条件返回true
,Click事件处理程序也总是执行else
分支,记录"Loser!"我敢肯定,在这种情况下,isFormNotEmpty
的价值确实是true
.
const handleClickOutside: EventListener = (event) => {
if (modalRef.current && !modalRef.current.contains(event.target as Node)) {
if (isFormNotEmpty) {
console.log("SUCCESS!");
const shouldClose = window.confirm("Some form fields are not empty. Do you really want to close the modal?");
if (shouldClose) {
hideModal();
}
} else {
console.log("LOOSER!");
hideModal();
}
}
};
useEffect(() => {
if (window) {
window.addEventListener("mousedown", handleClickOutside);
return () => {
window.removeEventListener("mousedown", handleClickOutside);
};
}
}, []);
有一个情态词
{isModalOpen && (
<div
className={`fixed top-0 left-0 right-0 bottom-0 flex justify-center items-center z-50 overflow-y-scroll ${
className && className
}`}>
<div className="fixed top-0 left-0 right-0 bottom-0 bg-black opacity-50"></div>
<div
className="relative w-full max-w-2xl max-h-full tablet-max:px-5"
ref={modalRef}>
<div className="relative bg-white rounded-lg shadow dark:bg-whiteText">
<div className="flex items-center justify-between p-4 border-b rounded-t dark:border-gray-600">
{lottie && <Lottie animationData={lottie} className="w-12" />}
<h3 className="text-xl font-semibold text-gray-900">{title}</h3>
<button
type="button"
className="text-gray-400 bg-transparent hover:bg-primary hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center"
onClick={hideModal}>
<svg
aria-hidden="true"
className="w-5 h-5"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg">
<path
fillRule="evenodd"
d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
clipRule="evenodd"></path>
</svg>
<span className="sr-only">Close modal</span>
</button>
</div>
<div className="p-2 space-y-6">{children}</div>
</div>
</div>
</div>
)}
我的目标是当单击发生在其边界之外时关闭该模式,除非某些表单域不为空.