我做了一个模态,如下所示:
export const Modal = ({ onClose, children, title = "" }) => {
const handleBackdropClick = (e) => {
e.target === e.currentTarget && onClose();
};
useEffect(() => {
document.body.style.overflow = "hidden";
return () => {
document.body.style.overflow = "unset";
};
}, []);
return (
<>
{/* Back drop */}
<div
className="fixed inset-0 flex justify-center items-top py-2 transition-opacity px-2 visible bg-slate-950 z-50 bg-opacity-50"
onClick={handleBackdropClick}
>
{/* Modal body */}
<div className="bg-white border-2 p-4 md:p-6 shadow-xl rounded-3xl w-full md:w-min overflow-y-auto min-h-fit h-max transform transition-all scale-100 opacity-100 ">
<div className="flex items-center justify-between sticky top-0 gap-8">
<h4 className="text-primary-text text-base md:text-xl font-bold w-max">
{title}
</h4>
<span className="cursor-pointer text-gray-500" onClick={onClose}>
<interfaceIcons.CloseIcon size="24" />
</span>
</div>
{children}
</div>
</div>
</>
);
};
这将被称为这样:
export const HomePage= () => {
const [isModalOpen, setIsModalOpen] = useState(false);
const handleModalOpen = () => {
setIsModalOpen(!isModalOpen);
};
return (
<>
<button onClick={handleModalOpen}>Open modal</button>
{isModalOpen && (
<Modal title="My modal" onClose={handleModalOpen}>
content here!
</Modal>
)}
</>
);
};
模式打开时我需要一个简单的动画。问题是当我们根据条件渲染时,动画不受影响。那么我怎样才能添加动画呢?
模式打开时我需要一个简单的动画。就像我下面给出的那样
ease-in-out delay-150 duration-300
问题是当我们根据条件渲染时,动画不受影响。 我需要这样的动画。
如果您有条件地添加和删除组件,则无法为其设置动画。
// animation effect will not work this way
{isModalOpen && (
<Modal title="My modal" onClose={handleModalOpen}>
content here!
</Modal>
)}
或者,要显示过渡,您可以使模态始终显示在 DOM 中,但使用 opacity-0
和
z-[-9999]
伪造 hidden样式,然后在
isModalOpen
的帮助下有条件地添加和删除这些类。
import { useEffect, useState } from 'react';
export const Modal = ({
onClose,
children,
title = '',
isModalOpen,
}) => {
const handleBackdropClick = (e: any) => {
e.target === e.currentTarget && onClose();
};
useEffect(() => {
document.body.style.overflow = 'hidden';
return () => {
document.body.style.overflow = 'unset';
};
}, []);
return (
<>
{/* Back drop */}
<div
className={`fixed inset-0 flex justify-center items-top py-2 transition-opacity px-2 visible z-50 bg-opacity-50 ${
!isModalOpen && 'opacity-0 z-[-9999]'
}`}
onClick={handleBackdropClick}
>
{/* Modal body */}
<div className="bg-white border-2 p-4 md:p-6 shadow-xl rounded-3xl w-full md:w-min overflow-y-auto min-h-fit h-max transform transition-all scale-100 opacity-100 ">
<div className="flex items-center justify-between sticky top-0 gap-8">
<h4 className="text-primary-text text-base md:text-xl font-bold w-max">
{title}
</h4>
<span className="cursor-pointer text-gray-500" onClick={onClose}>
close
</span>
</div>
{children}
</div>
</div>
</>
);
}
// notice I also passed "isModalOpen" to control show/hide
<Modal title="My modal" isModalOpen={isModalOpen} onClose={handleModalOpen}>
content here!
</Modal>
这是 Stackblitz 上的 工作片段