安装Framer Motion后NextJS组件动画出现元素类型无效错误求助
解决NextJS中使用Framer Motion出现的「Element type is invalid」错误
这个错误核心原因是Framer Motion的导入方式不匹配NextJS路由模式,或是版本兼容性问题,以下是针对性解决步骤:
修正导入方式(适配NextJS 13+ App Router)
如果你用的是NextJS 13及以上的App Router,直接从framer-motion导入motion会导致客户端组件识别异常,需要改为从framer-motion/dom导入:import { motion } from 'framer-motion/dom';若是Pages Router模式,保持原导入方式即可。
重新安装兼容版本的依赖
卸载现有Framer Motion后,安装最新兼容版本:npm uninstall framer-motion npm install framer-motion@latest用Yarn或PNPM的话:
yarn remove framer-motion yarn add framer-motion@latest配置NextJS兼容App Router
在next.config.js中添加转译配置,确保Framer Motion的客户端组件能正常编译:/** @type {import('next').NextConfig} */ const nextConfig = { transpilePackages: ['framer-motion'], }; module.exports = nextConfig;
修正后的示例代码
import { motion } from 'framer-motion/dom'; const HeroSection: React.FC = () => { return ( <div className="text-white py-10 overflow-hidden"> <div className="container mx-auto px-6 flex flex-col lg:flex-row items-center"> <motion.div className="w-full lg:w-3/5 mb-12 lg:mb-0" initial={{ opacity: 0, x: -50 }} animate={{ opacity: 1, x: 0 }} transition={{ duration: 0.6, ease: "easeOut" }} > {/* 在此添加你的组件内容 */} </motion.div> </div> </div> ); }; export default HeroSection;
内容的提问来源于stack exchange,提问作者oyerohabib
相关产品推荐
相关产品推荐

