Javascript 使用 JSX 在 React 中显示图像而无需导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42580130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display images in React using JSX without import
提问by Gayathri
The problem i face is with img tag. When a single is concerned, The below code loads the image:
我面临的问题是 img 标签。当单是关心时,下面的代码加载图像:
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'}] and display each of them as image with name as footer. Looping is fine but images doesn't load.It is not actually possible for myself to import every images to add. I don't use anything other than JSX as of now.Please favour.
我需要遍历 json ,类似于 [{'img':'./images/image1.jpg','name':'AAA'},{'img':'./images/image2.jpg',' name':'BBB'}] 并将它们显示为图像,名称为页脚。循环很好,但图像无法加载。我自己实际上不可能导入要添加的每个图像。目前我不使用 JSX 以外的任何东西。请支持。
回答by Win
You need to require the file like so:
您需要像这样要求文件:
<img src={ require('./images/image1.jpg') } />
回答by Robsonsjre
requireis used for static "imports", so you just need to change your imports.
require用于静态“导入”,因此您只需要更改imports.
Example:
例子:
var imageName = require('./images/image1.jpg')
<img src={imageName} />
回答by Daniel C. Deng
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;
}
}
回答by Don-Pierre Halfaway
import React from "react";
var imageName = require('./images/jsx_Photo.jpg')
const about = () => (
<form>
<img src={imageName} />
</form>
);
export default about;
{/*I did not see the title where it said no importing until after I
{/* checked my work, however*/}
{/*I thought I leave this comment up for those who find it like I */}
{/* did by mistake *}
{/* and want to quickly have a functional photo up and use object*/}
{/*destructuring */}
{/*make sure you have the core file within the correct path */}

