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

如何在Vite+React项目中从JSON文件动态加载图片?

解决Vite+React中静态图片无法渲染的问题

问题原因

JSON文件里的logo路径是相对于JSON自身所在位置(assets/data)的../images/xxx.svg,但组件(components/CardWrapper)使用这个路径时,会以组件所在位置为基准去查找,导致实际查找路径错误——虽然网络返回304状态码,但浏览器无法定位到正确的图片资源。

可行解决方案

方案1:利用Vite的import.meta.url解析绝对路径

  1. 修改JSON中的logo路径为基于项目根目录的绝对路径:
    "logo": "/src/assets/images/the-air-filter-company.svg"
    
  2. 在CardWrapper组件中通过new URL处理路径:
    const CardWrapper = ({ company }) => {
        return (
            <figure className={styles.figureJobCard}>
                <img 
                    src={new URL(company.logo, import.meta.url).href} 
                    alt='company svg' 
                    width={70} 
                    height={70} 
                />
                {/* 其余组件代码 */}
            </figure>
        )
    }
    

方案2:修正组件中的相对路径

直接在组件里将JSON中的路径转换为相对于组件的正确路径:

const CardWrapper = ({ company }) => {
    // 将JSON里的../images/替换为从组件到assets/images的相对路径
    const logoPath = company.logo.replace('../images/', '../../assets/images/');
    return (
        <figure className={styles.figureJobCard}>
            <img 
                src={logoPath} 
                alt='company svg' 
                width={70} 
                height={70} 
            />
            {/* 其余组件代码 */}
        </figure>
    )
}

方案3:将图片移至public目录

  1. 在项目根目录创建public/images文件夹,把所有logo图片移进去。
  2. 修改JSON中的logo路径为根相对路径:
    "logo": "/images/the-air-filter-company.svg"
    
  3. 组件中直接使用该路径即可,无需额外处理:
    <img src={company.logo} alt='company svg' width={70} height={70} />
    

内容的提问来源于stack exchange,提问作者daniel sas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:26:25