不使用 JSON 对象作为参考在 React 上加载图像

问题描述 投票:0回答:2

这是我的问题

我有下面这个对象Json:

const imagesData = [
    {
        "imagepath": "./images/a.jpg",
        "title": "Red Car",
        "uploadeDate": "2 May 2020",
        "index": "0"
    }, {
        "imagepath": "./images/b.jpg",
        "title": "Blue Car",
        "uploadeDate": "2 May 2020",
        "index": "1"
    }, {
        "imagepath": "./images/c.jpg",
        "title": "Green Car",
        "uploadeDate": "2 May 2020",
        "index": "2"
    }

]

所以我的代码使用这个名为“imagepath”的对象的属性来在标签 img 的 src 上使用它

const card = imagesData.map(function (obj, ind) {
       
        return (
            <div className='card'>
                <img src={obj.imagepath} />
                <span>{obj.title}</span>
            </div>
        )

所以问题是图像没有加载,我已经检查了路径,它是正确的

这是它在我的屏幕上显示的图片:

enter image description here

一个观察是,如果我尝试通过以下方式导入图像

 import car1 from './images/a.jpg

在此之后我将变量 car1 如下所示

<img src={car1} />

效果很好!但我需要一个解决方案,从 json 对象引用图像的路径!

javascript json reactjs image src
2个回答
1
投票

我认为你应该将图像文件夹保留在公共文件夹中,然后你可以直接尝试此操作而无需导入。

const imagesData = [
    {
        "imagepath": '/images/a.jpg',
        "title": "Red Car",
        "uploadeDate": "2 May 2020",
        "index": "0"
    }, {
        "imagepath": '/images/b.jpg',
        "title": "Blue Car",
        "uploadeDate": "2 May 2020",
        "index": "1"
    }, {
        "imagepath": '/images/c.jpg',
        "title": "Green Car",
        "uploadeDate": "2 May 2020",
        "index": "2"
    }

]

0
投票

找到让它发挥作用的方法了吗?非常感谢您的帮助。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.