You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS13 App Dir中Framer Motion页面过渡动画异常求助

NextJS 13 App Dir + Framer Motion 页面过渡动画问题解决

问题核心

切换路由时新页面内容在当前页淡出动画完成前加载,导致闪现,期望实现「当前页先淡出 → 路由切换完成 → 新页淡入」的顺序。

解决方案

1. 根布局配置AnimatePresence

在app/layout.tsx中,用AnimatePresence包裹页面内容,设置mode="wait"确保退出动画完成后再渲染新页面,同时给每个页面绑定唯一的路由路径作为key:

'use client';

import { AnimatePresence } from 'framer-motion';
import { usePathname } from 'next/navigation';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();

  return (
    <html lang="zh-CN">
      <body>
        <AnimatePresence mode="wait">
          {React.cloneElement(children as React.ReactElement, { key: pathname })}
        </AnimatePresence>
      </body>
    </html>
  );
}

2. 页面组件添加动画属性

每个页面组件(如app/page.tsx、app/about/page.tsx)需标记为客户端组件,并配置initial、animate、exit动画参数:

'use client';

import { motion } from 'framer-motion';
import Link from 'next/link';

export default function Home() {
  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      transition={{ duration: 0.5 }}
      className="min-h-screen p-8"
    >
      <h1>首页</h1>
      <Link href="/about" className="mt-4 inline-block">前往关于页</Link>
    </motion.div>
  );
}

关键注意点

  • 所有涉及动画的页面和布局必须添加'use client'指令,因为Framer Motion依赖客户端渲染。
  • AnimatePresence的mode="wait"是核心:它会暂停新组件的进入动画,直到旧组件的退出动画完全结束。
  • 给每个页面绑定key={pathname}是为了让AnimatePresence识别路由变化,触发组件的卸载/挂载动画。

内容的提问来源于stack exchange,提问作者dan2017

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 18:55:08