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

Next.js搭配Framer Motion实现页面切换时退出动画不生效求助

核心问题原因

AnimatePresence 需要检测到直接子元素的 key 属性发生变更,才会触发旧子元素的退出动画。你当前没有给传入 Layout 的页面组件绑定唯一标识,Framer Motion 无法识别页面发生了切换,因此不会执行淡出逻辑。

修复步骤

  1. 修改 /pages/_app.js,给页面组件绑定路由唯一key
    引入useRouter钩子,将路由路径作为页面组件的唯一key,保证路由切换时key会同步变化:
import { useRouter } from 'next/router'

function MyApp({ Component, pageProps }) {
  const router = useRouter()
  return (
      <Layout>
        <Component {...pageProps} key={router.asPath} />
      </Layout>
  )
}

export default MyApp
  1. 适配Framer Motion版本的AnimatePresence配置(按需修改)
    如果你使用的是 Framer Motion v4及以上版本,原有的exitBeforeEnter布尔属性已经废弃,需要替换为mode参数,修改/shared/layout.js中的AnimatePresence配置:
// v4+版本写法
<AnimatePresence mode="wait">
  { children }
</AnimatePresence>

// v3及以下版本保持原有的exitBeforeEnter写法即可

其他注意事项

  • 你当前/pages/contact.js中根motion.div的id误写为了home,建议修正为contact避免后续样式/逻辑冲突
  • 确保所有页面的motion.div、Layout中的AnimatePresence都是从framer-motion包正确导入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:36:03