在NextJS 13中使用Framer Motion进行页面过渡

pu82cl6c  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(153)

我正在使用NextJS 13与App Dir。我有成帧运动安装,并试图实现淡出/淡入页面过渡,但经过许多许多小时试图让这工作,我正式卡住了!
我面临的主要问题是,在改变路由时,新的页面内容似乎在退出(淡出)动画触发之前加载,这导致在淡出之前对新页面内容的短暂一瞥,然后再次进入。显然,我在这里试图实现的是,当我点击一个元素时,页面内容将淡出,路径将改变,然后新页面的内容将淡入。
我可以在这里提供我的代码,但我也创建了一个代码沙箱链接来说明我的问题:https://codesandbox.io/p/sandbox/awesome-wiles-9vmdyx

// PageTransition.js
"use client"
import { AnimatePresence, motion } from "framer-motion";

const variants = {
  hidden: { opacity: 0 },
  enter: { opacity: 1, transition: { duration: 0.4 } },
  exit: { opacity: 0, transition: { duration: 0.4 } },
};

export default function PageTransition({ children, path }) {
  return (
    <AnimatePresence mode='wait'>
      <motion.div
        key={path}
        variants={variants}
        initial="hidden"
        animate="enter"
        exit="exit"
      >
        {children}
      </motion.div>
    </AnimatePresence>
  );
}

// layout.js
"use client"
import "./styles/globals.scss";
import "bootstrap/dist/css/bootstrap.min.css";
import localFont from "next/font/local";
import Header from "./components/common/Header";
import Footer from "./components/common/Footer";
import PageTransition from "./components/animate/PageTransition";
import { usePathname } from "next/navigation";

const fedraSerif = localFont({
  src: "./fonts/FedraSerifAPro-Bold.ttf",
  display: "swap",
  variable: "--font-fedraSerif",
});

const fsMe = localFont({
  src: "./fonts/FS Me-Regular.otf",
  display: "swap",
  variable: "--font-fsMe",
});

export default function RootLayout({ children }) {
  const activePath = usePathname();
  return (
    <html lang="en" className={`${fedraSerif.variable} ${fsMe.variable}`}>
      <body>
        <Header />
        <PageTransition path={activePath}>
          {children}
        </PageTransition>
        <Footer />
      </body>
    </html>
  );
}

有人能帮忙吗?Tia

bz4sfanl

bz4sfanl1#

可以使零部件平滑显示,如下所示。
添加一个class .page-transition并设置样式:

.page-transition {
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

在应该平滑消失的组件中,我们添加usePageTransition

export const usePageTransition = () => {
  document.querySelectorAll(".page-transition").forEach((item) => {
   item.style.opacity = 1;
  });
};

首页:

"use client";

import Image from "next/image";
import { useEffect } from "react";
import { usePageTransition } from "./hooks/usePageTransition";

export default function Home() {
  useEffect(() => {
    usePageTransition();
  }, []);
  return (
    <main className="home page-transition">
      <h1>Home Page</h1>
      <Image src="/man.png" width={500} height={500} />
    </main>
  );
}

https://codesandbox.io/p/sandbox/showpagetransitionnext13-m5n2wt

相关问题