简体   繁体   English

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

[英]Not loading images on React using a JSON object as reference

this is my problem这是我的问题

I have this object Json below:我在下面有这个对象 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"
    }

]

So my code is using the property of this object called "imagepath" to use it on the src of the tag img所以我的代码使用这个名为“imagepath”的对象的属性在标签 img 的 src 上使用它

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

so the problem is that the images are not loading, i have already checked the path and it is right所以问题是图像没有加载,我已经检查了路径并且是正确的

this is a picture of how it shows on my screen:这是它如何在我的屏幕上显示的图片:

在此处输入图片说明

One observation is that if i try to import the images by import car1 from './images/a.jpg一个观察结果是,如果我尝试通过import car1 from './images/a.jpg来导入图像

and after this i put the variable car1 like below <img src={car1} />在此之后,我将变量 car1 如下<img src={car1} />

it works fine !.它工作正常! But i need a solution that i reference that path of the image from a json object !但我需要一个解决方案,我从 json 对象引用图像的路径!

I think you should keep your images folder in the public Folder and then you can try this directly without importing.我认为您应该将图像文件夹保存在公共文件夹中,然后您可以直接尝试而无需导入。

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"
    }

]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM