Display images in React using JSX without import

早过忘川 提交于 2019-11-27 02:31:45

问题


The problem i face is with img tag. When a single 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'}] 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.


回答1:


You need to require the file like so:

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



回答2:


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

Example:

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



回答3:


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


来源:https://stackoverflow.com/questions/42580130/display-images-in-react-using-jsx-without-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!