[英]How to use Framer Motion <AnimatePresence> and React Portals?
I built a React Modal component using React Portals (see Docs above).我使用React Portals构建了一个 React Modal组件(参见上面的文档)。 Before unmounting the component when the close button is clicked, I want to run an exit
animation with Framer Motion using AnimatePresence .在单击关闭按钮时卸载组件之前,我想使用AnimatePresence使用 Framer Motion 运行exit
动画。 Unfortunately, I can't make it work and need help.不幸的是,我无法让它工作,需要帮助。
I added
exit={{ opacity: 0 }}
to a child of<RenderModal/>
.我将exit={{ opacity: 0 }}
到<RenderModal/>
的孩子。 The entering animation usinginitial
andanimate
worked as expected.使用initial
和animate
的进入动画按预期工作。
<AnimatePresence>
around modal-root element将<AnimatePresence>
包裹在 modal-root 元素周围<div id="root"></div>
<AnimatePresence>
<div id="modal-root"></div>
</AnimatePresence>
Error: Target container requires a DOM element错误:目标容器需要 DOM 元素
<div id="modal-root">
<AnimatePresence></AnimatePresence>
</div>
const Modal = ({
title,
footer,
children,
}) => {
<AnimatePresence>
{isVisible
&& (
<RenderModal
title={title}
footer={footer}
hide={hide}
>
{children}
</RenderModal>
)}
</AnimatePresence>
};
return (
<>
<Button onClick={show}>Open Modal</Button>
<AnimatePresence>
<Modal {...args}></Modal>
</AnimatePresence>
<p>Lorem ipsum dolor sit amet...</p>
</>
);
Hello I think might be late.你好,我想可能会迟到。 but I solve with this code但我用这段代码解决了
import { ReactNode } from "react";
import ReactDOM from "react-dom";
import { AnimatePresence } from "framer-motion";
interface ModalWrapperProps {
children: ReactNode;
isShowing: boolean;
}
const ModalWrapper = ({ children, isShowing }: ModalWrapperProps) =>
ReactDOM.createPortal(
<AnimatePresence exitBeforeEnter>
{isShowing && children}
</AnimatePresence>,
document.body
);
export default ModalWrapper;
I inspired below post我启发了下面的帖子
https://blog.logrocket.com/implementing-animated-toasts-in-react/ https://blog.logrocket.com/implementing-animated-toasts-in-react/
Did you remember to include a key
prop for the conditionally rendered element?您是否记得为条件渲染元素包含一个key
道具? I don't see it in your code snippets.我在你的代码片段中没有看到它。
Child motion components must each have a unique key prop so AnimatePresence can track their presence in the tree.子运动组件必须每个都有一个唯一的关键道具,以便 AnimatePresence 可以跟踪它们在树中的存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.