简体   繁体   English

使用 JSX 在 React 中显示图像而无需导入

[英]Display images in React using JSX without import

The problem I faced is with the img tag.我面临的问题是img标签。 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:我需要遍历 json,例如:

[{'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.到目前为止,我不使用 JSX 以外的任何东西。 Please favour.请赐教。

您需要像这样要求文件:

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

require is used for static "imports", so you just need to change your imports . require用于静态“导入”,因此您只需要更改imports

Example:例子:

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

We could use require instead of import statment.我们可以使用 require 代替 import 语句。 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我们可以通过添加.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第二个显示 alt“要求功能失败” - 不是预期的结果

Its because, you've put your images folder in src folder.这是因为,您已将图像文件夹放在 src 文件夹中。 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.直接把图片来源放到public文件夹下就可以了,不用导入或使用require,像这样。

<img src='/images/image1.jpg' /> <img src='/images/image1.jpg' />

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

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