简体   繁体   中英

Display images in React using JSX without import

The problem I faced is with the img tag. When a single image is concerned, The below code loads the image:

import image1 from './images/image1.jpg';
<img src={image1} />

But the below code doesn't load:

 <img src={'./images/image1.jpg'}/>
            or
  <img src='./images/image1.jpg'/>

I need to loop through json, something like:

[{'img':'./images/image1.jpg','name':'AAA'}, {'img':'./images/image2.jpg','name':'BBB'}]

Plus, display each of them as image with name as footer. Looping is fine but the images doesn't load. It is not actually possible for me to import every images to add. I don't use anything other than JSX as of now. Please favour.

您需要像这样要求文件:

<img src={ require('./images/image1.jpg') } />

require is used for static "imports", so you just need to change your imports .

Example:

var imageName = require('./images/image1.jpg')
<img src={imageName} />

We could use require instead of import statment. Like ,

<img src={require("folder/image.format")} alt="image not found" />

But if you run it , it will show image not found!!!

We could simply solve it by changing the statment by adding .default

let image = require("folder/image.format");

<img src={image.default} alt="image not found" />

I just tried this, it works!

import I01d from '../../styles/images/01d.png';
....
<img src={this.getWeatherIconImage(iconCode)}/>

getWeatherIconImage(icon) {
  switch (icon) {
    case '01d': return I01d; ...
    default: break;
  }
}

The suggested answers do not appear to work any more. Here is a code fragment that highlight the issue.

import React from 'react';
import importImg from '../images/img.jpg';
export default function ImgTest(){
return(<>
<img src={importImg} alt='import'></img><br/>
<img src={require('../images/img.jpg')} alt='require function fails'></img><br/>
</>)
}

When this code is rendered, the following occurs.

1st displays the image - it the expected result

2nd displays the alt "require function fails" - is not the expected result

Its because, you've put your images folder in src folder. So you should import or require it. You can directly put the source of image if it's placed in public folder without importing or using require, like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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