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

React中通过data.js映射图片路径无法正常加载的问题

React项目中图片无法加载的问题解决

问题场景

在React项目里,将data.js作为模拟数据库,导出包含coverImg图片路径属性的对象数组。在App.js中导入该数组并通过.map()方法将coverImg作为img属性传递给Card组件,但图片无法正常加载,也没有“找不到图片”的错误。只有通过import imgSource from './images/image.png'的方式导入图片路径,才能正常显示图片。images文件夹位于src目录下。

相关代码

App.js

import React from "react";
import data from './data';

export default function App() {
const cards = data.map(card => {
    return <Card
        key={card.id}
        name={card.name}
        img={card.coverImg}
        rating={card.stats.rating}
        reviewCount={card.stats.reviewCount}
        country={card.location}
        title={card.title}
        price={card.price}
    />
});

return (
    <div>
        {cards}
    </div>
)
}

data.js

export default [
{
    id: 1,
    title: "Life Lessons with Katie Zaferes",
    description: "I will share with you what I call \"Positively Impactful Moments of Disappointment.\" Throughout my career, many of my highest moments only came after setbacks and losses. But learning from those difficult moments is what gave me the ability to rise above them and reach my goals.",
    price: 136,
    coverImg: "./images/katie-zafares.jpg",
    stats: {
        rating: 5.0,
        reviewCount: 6
    },
    location: "Online",
    openSpots: 0,
},
{
    id: 2,
    title: "Learn Wedding Photography",
    description: "Interested in becoming a wedding photographer? For beginner and experienced photographers alike, join us in learning techniques required to leave the happy couple with memories that'll last a lifetime.",
    price: 125,
    coverImg: "./images/wedding-photography.png",
    stats: {
        rating: 5.0,
        reviewCount: 30
    },
    location: "Online",
    openSpots: 27,
},
{
    id: 3,
    title: "Group Mountain Biking",
    description: "Experience the beautiful Norwegian landscape and meet new friends all while conquering rugged terrain on your mountain bike. (Bike provided!)",
    price: 50,
    coverImg: "./images/mountain-bike.png",
    stats: {
        rating: 4.8,
        reviewCount: 2
    },
    location: "Norway",
    openSpots: 3,
}
]

Card组件

import React from 'react';
import star from '../images/star.png';

export default function Card(props) {
    return (
        <div className="card">
            <img src={props.img} alt={props.name}/>
            <div>
                <div className="score">
                    <img src={star} alt="star"/>
                    <strong>{props.rating}</strong>
                    <p className="faded-font">({props.reviewCount}) • {props.country}</p>
                </div>
                <p>{props.title}</p>
                <strong>
                    From ${props.price} <p className="faded-font" id="person"> / person</p>
                </strong>
            </div>
        </div>
    )
}

问题原因

React项目使用的打包工具(如Webpack)会对src目录下的静态资源进行处理:它会给资源文件重命名(添加哈希值),并生成打包后的正确路径。直接在data.js里写相对路径的话,打包工具无法识别这是需要处理的资源路径,导致最终页面里的图片路径还是原始的相对路径,和打包后的实际资源路径不匹配,所以图片加载不出来。而用import导入图片时,打包工具会自动解析路径,将其替换为打包后的正确URL,因此能正常显示。

解决方法

方法一:在data.js中用require引入图片路径

修改data.js里的coverImg属性,用require加载图片,这样打包工具会正确处理路径:

export default [
{
    id: 1,
    title: "Life Lessons with Katie Zaferes",
    description: "I will share with you what I call \"Positively Impactful Moments of Disappointment.\" Throughout my career, many of my highest moments only came after setbacks and losses. But learning from those difficult moments is what gave me the ability to rise above them and reach my goals.",
    price: 136,
    coverImg: require('./images/katie-zafares.jpg'),
    stats: {
        rating: 5.0,
        reviewCount: 6
    },
    location: "Online",
    openSpots: 0,
},
{
    id: 2,
    title: "Learn Wedding Photography",
    description: "Interested in becoming a wedding photographer? For beginner and experienced photographers alike, join us in learning techniques required to leave the happy couple with memories that'll last a lifetime.",
    price: 125,
    coverImg: require('./images/wedding-photography.png'),
    stats: {
        rating: 5.0,
        reviewCount: 30
    },
    location: "Online",
    openSpots: 27,
},
{
    id: 3,
    title: "Group Mountain Biking",
    description: "Experience the beautiful Norwegian landscape and meet new friends all while conquering rugged terrain on your mountain bike. (Bike provided!)",
    price: 50,
    coverImg: require('./images/mountain-bike.png'),
    stats: {
        rating: 4.8,
        reviewCount: 2
    },
    location: "Norway",
    openSpots: 3,
}
]

方法二:在Card组件中动态加载图片

如果不想修改data.js,可以在Card组件里通过require动态加载图片。先把data.js里的coverImg改成只存文件名(比如katie-zafares.jpg),然后修改Card组件的img标签:

// 修改后的Card组件img部分
<img src={require(`../images/${props.img}`)} alt={props.name}/>

如果不想改data.js里的路径,也可以通过字符串截取获取文件名:

// 直接处理原路径
const imgFileName = props.img.split('/')[2];
<img src={require(`../images/${imgFileName}`)} alt={props.name}/>

方法三:将图片放到public文件夹(不推荐)

把images文件夹移到项目根目录的public文件夹下,然后修改data.js里的路径为/images/katie-zafares.jpg。这种方式打包工具不会处理图片资源,也不会进行优化,所以一般不推荐使用。

内容的提问来源于stack exchange,提问作者Alin-Alexandru Peter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:03:22