使用Framer Motion与Next.js时本地图片无法显示问题求助
解决Next.js + Framer Motion本地图片不显示的问题
方案1:修正本地图片导入后的取值方式
如果使用Next.js 13+ App Router,导入本地图片后返回的是包含src、width等属性的元数据对象,而非直接URL,需修改src的取值逻辑:
import React from 'react' import {motion} from "framer-motion"; import aboutPic from './images/wed.jpg' type Props = {} function About({}: Props) { return ( <div className=" flex flex-col relative h-screen text-center md:text-left md:flex-row max-7xl px-10 justify-evenly mx-auto items-center"> <h3 className="absolute top-24 uppercase tracking-[20px] text-gray-500 text-2xl"> About </h3> <motion.img initial={{x:-200}} transition={{duration:1.2}} whileInView={{x: 0}} src={aboutPic.src} {/* 改为取对象的src属性 */} alt="About section image" {/* 必须添加alt属性,保障可访问性 */} /> </div> ) } export default About
方案2:结合Next.js Image组件使用(推荐)
Next.js官方Image组件会自动处理本地图片的优化、加载逻辑,配合Framer Motion包装使用更稳定:
import React from 'react' import {motion} from "framer-motion"; import Image from 'next/image' import aboutPic from './images/wed.jpg' type Props = {} // 用motion包装Image组件,保留动画能力 const MotionImage = motion(Image) function About({}: Props) { return ( <div className=" flex flex-col relative h-screen text-center md:text-left md:flex-row max-7xl px-10 justify-evenly mx-auto items-center"> <h3 className="absolute top-24 uppercase tracking-[20px] text-gray-500 text-2xl"> About </h3> <MotionImage initial={{x:-200}} transition={{duration:1.2}} whileInView={{x: 0}} src={aboutPic} alt="About section image" width={500} {/* 根据需求设置尺寸,或用className控制 */} height={500} className="object-cover" /> </div> ) } export default About
额外排查点
- 确认图片路径正确:
./images/wed.jpg与组件文件的相对路径匹配,且图片文件确实存在于对应目录。 - 检查
next.config.js:若为App Router,确保没有错误配置图片域名限制(本地图片无需额外域名配置)。 - 版本兼容性:确认安装了最新版的
framer-motion和next,避免版本不兼容导致的问题。
内容的提问来源于stack exchange,提问作者Jerm
相关产品推荐
相关产品推荐

