NextJS v13(Pages目录)中Framer Motion动画无法运行求助
问题:NextJS v13 Pages目录中Framer Motion挥手动画不生效
在NextJS v13(Pages目录)项目中,尝试给Hero组件添加挥手动画,但仅显示静态👋 emoji,无动画效果。
WavingHand组件代码:
import { motion } from 'framer-motion'; export default function WavingHand() { return ( <motion.div style={{ marginBottom: '-20px', marginRight: '-45px', paddingBottom: '20px', paddingRight: '45px', display: 'inline-block', }} animate={{ rotate: 20 }} transition={{ yoyo: Infinity, from: 0, duration: 0.2, ease: 'easeInOut', type: 'tween', }} > 👋 </motion.div> ); }
Hero组件中调用代码:
<Typography component={motion.h1} variant="h1" sx={{ fontSize: { md: '4rem', sm: '3rem', xs: '3rem' }, textAlign: { xs: 'center', sm: 'initial' }, }} > Hello <WavingHand /> ! </Typography>;
已尝试用motion.div包裹整个Typography元素,但动画仍无法运行。
解决方案
1. 修正动画配置错误
transition配置中的from属性不属于该字段,需将初始状态移至initial属性中,同时添加旋转原点让动画更符合挥手逻辑:
import { motion } from 'framer-motion'; export default function WavingHand() { return ( <motion.div style={{ marginBottom: '-20px', marginRight: '-45px', paddingBottom: '20px', paddingRight: '45px', display: 'inline-block', transformOrigin: 'bottom right', // 设置旋转原点,模拟真实挥手动作 }} initial={{ rotate: 0 }} // 初始旋转角度 animate={{ rotate: 20 }} // 目标旋转角度 transition={{ yoyo: Infinity, duration: 0.2, ease: 'easeInOut', type: 'tween', }} > 👋 </motion.div> ); }
2. 添加客户端组件指令
NextJS Pages目录默认服务端渲染,Framer Motion动画需要在客户端执行,给WavingHand组件顶部添加'use client'指令:
'use client'; // 必须放在组件最顶部 import { motion } from 'framer-motion'; export default function WavingHand() { // ... 组件代码 }
3. 验证依赖兼容性
确保安装的framer-motion版本适配NextJS v13,执行更新命令:
npm install framer-motion@latest # 或 yarn add framer-motion@latest
4. 排除父组件样式干扰
临时替换Typography组件为普通h1标签,测试动画是否正常:
<h1 style={{ fontSize: '4rem' }}> Hello <WavingHand /> ! </h1>
内容的提问来源于stack exchange,提问作者DhruvK
相关产品推荐
相关产品推荐

