How to give Image src dynamically in react js?

放肆的年华 提交于 2020-03-18 04:08:04

问题


I am trying to give image name in src dynamically. I want to set image name dynamically using variable with path. but I am not able to set src correctly. I tried solutions on stackoverflow but nothing is working.

I tried to give path like this

<img src={`../img/${img.code}.jpg`}></img>

<img src={'../img/' + img.code + '.jpg'}></img>

<img src={'../img/{img.code}.jpg'}></img>

my images are saved in src/img path if i give path like this

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

image is showing

I know this question is asked before but nothing is working for me. Please help me how can I set image path?


回答1:


if you dont want to require the image then you have to put all your images into public folder and then

<img src={`../img/${img.code}.jpg`}></img>

this method will work.




回答2:


You can still use require

<img src={require(`./img/${img.code}.jpg`)}/>

It's not recommended to manually add images to the public folder. See this answer here: https://stackoverflow.com/a/44158919/1275105




回答3:


If you guys get the path from the database for multiple images and need to use in single tag, you can follow the below method. step 1 : Please make sure the images are in public folder. step 2 : Update your path should start from public not from src. step 3 : Make sure to verify that the path should be using like a variable. If your images path should be using in variable imgPath. You can use your code like var imgPath = '/img/pic.jpeg' "src={imgPath}"

I hope this will help you..



来源:https://stackoverflow.com/questions/54033765/how-to-give-image-src-dynamically-in-react-js

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