简体   繁体   English

如何使用 Framer Motion<AnimatePresence> 和 React 门户?

[英]How to use Framer Motion <AnimatePresence> and React Portals?

Situation情况

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.不幸的是,我无法让它工作,需要帮​​助。

Links链接

What I tried我试过的

I added exit={{ opacity: 0 }} to a child of <RenderModal/> .我将exit={{ opacity: 0 }}<RenderModal/>的孩子。 The entering animation using initial and animate worked as expected.使用initialanimate的进入动画按预期工作。

  1. Wrap <AnimatePresence> around modal-root element<AnimatePresence>包裹在 modal-root 元素周围
<div id="root"></div>
<AnimatePresence>
  <div id="modal-root"></div>
</AnimatePresence>
  1. Wrap as child of modal-root包装为 modal-root 的孩子

Error: Target container requires a DOM element错误:目标容器需要 DOM 元素

<div id="modal-root">
  <AnimatePresence></AnimatePresence>
</div>
  1. Wrap around the component element环绕组件元素
const Modal = ({
    title,
    footer,
    children,
  }) => {
   <AnimatePresence>
    {isVisible
      && (
        <RenderModal
          title={title}
          footer={footer}
          hide={hide}
        >
          {children}
        </RenderModal>
      )}
    </AnimatePresence>
  };
  1. Wrap around the used Component环绕使用过的组件
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.我在你的代码片段中没有看到它。

From the docs :文档

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM