React中列表对象图片作为Props传递显示缺失问题求助
问题解决:React组件间传递图片时显示缺失
问题根源
你在projects数组里把导入的图片变量包装成了对象(比如picture: { chatroom }),但React中导入的图片本身就是一个字符串格式的解析后URL,直接传递对象给img的src属性会导致无法识别,所以图片显示缺失。
修复步骤
修正projects数组的图片属性
把每个项目的picture值从对象改为直接使用导入的图片变量:const projects = [ { name: "Real-Time-Chatroom", type: "Web Page", description: "Discord-like webpage that allows for several different users to send messages to a variety of different servers/chatrooms.", picture: chatroom, // 直接用变量,不要包成对象 }, { name: "Weather App", type: "Web Page", description: "Weather application that uses user's location to find the correct weather, and display that information on screen, with CSS styling that changes depending on the weather conditions of the user's area.", picture: weather_app, // 直接用变量,不要包成对象 }, ];遍历数组时正确传递图片prop
在Portfolio组件中遍历projects数组时,将project.picture作为imageprop传给Project组件:// Portfolio组件中的渲染部分 {projects.map((project, index) => ( <Project key={index} name={project.name} type={project.type} description={project.description} image={project.picture} // 传递解析后的URL字符串 /> ))}确认Project组件的接收逻辑
你的Project组件代码已经正确接收imageprop并赋值给img的src,这部分无需修改:const Project = ({ name, type, description, image }) => { return ( <div className="project"> <h1>{name}</h1> <img src={image} alt={name}/> </div> ); };
原理说明
当你在React中使用import导入图片时,Webpack(或Vite等构建工具)会将图片文件处理为可访问的URL字符串,直接把这个字符串传给img的src就能正常显示图片。如果把它包装成对象,src得到的是一个对象而非URL,浏览器无法加载,就会显示缺失状态。
内容的提问来源于stack exchange,提问作者Sami
相关产品推荐
相关产品推荐

