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

如何将图片资源从一个JS文件导入到另一个React组件JS文件中使用?

问题原因
  • 导入路径不匹配:你存储图片常量的文件名为image.js,但在Track.js中导入时写的是./srcimages.js,路径对应不上导致导入的变量为undefined,最终img的src属性为空。
  • 图片常量文件未对外导出变量:你在image.js中仅声明了两个const变量,没有配置导出规则,外部文件无法正常引入变量值。
解决方法

第一步:修改image.js添加导出规则

推荐使用命名导出的方式,和你现有导入语法适配:

// image.js 完整代码
export const screenimage = 'https://image.shutterstock.com/image-illustration/shopping-online-concept-modern-design-260nw-1934432345.jpg';
export const screenimage1 = 'https://www.publicdomainpictures.net/pictures/320000/velka/background-image.png';

如果需要统一管理所有图片资源导出,也可以使用默认导出写法:

// image.js 可选写法
const screenimage = 'https://image.shutterstock.com/image-illustration/shopping-online-concept-modern-design-260nw-1934432345.jpg';
const screenimage1 = 'https://www.publicdomainpictures.net/pictures/320000/velka/background-image.png';

export default {
  screenimage,
  screenimage1
}
// 对应导入语法调整为 import images from './image.js',使用时写 src={images.screenimage} 即可

第二步:修改Track.js的导入路径

将导入路径调整为实际的图片常量文件路径:

import React from 'react'
// 路径修改为实际的image.js
import { screenimage, screenimage1 } from "./image.js";

function Track() {
    return (
        <div>
            Hello Component
            <img src={screenimage} alt=""/>
            <img src={screenimage1} alt=""/>
        </div>
    )
}

export default Track

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:45:02