Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - require function not working with image in react

I've used <img src={require('./somRelativePath/image.jpg)} in React many times. However, this time it seems not to be working. There are no errors whatsoever (such as that the image was not found etc.) but the broken image on website.

After inspecting the element I was somewhat confused by the transpiled result in browser:

<img src="[object Module]" style="width: 5rem;">

It appears as if it loads the image as a component not the acutual file. I've created the app with npx create-react-app and haven't ejected it so far. So there is no error in babel or webpack configuration as it is currently handled by react under the hood.

Importing it with import statement works just fine:

import calendarPic from '../assets/pictures/calendar.svg';

Unfortunately that's not the solution because I have the local images saved in json and it would be definitely quite repetitive and ineffective as well to load all 50 images.

With the same npx create-react-app I've made a handful of mini-projects before but have never come across such a perplexing, yet so basic error. I'd be so thankful for any response as I've skimmed every possible solution throughout the internet.

Thank you again and have a lovely day!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use this one, it's work for me

<img src={require('./somRelativePath/image.jpg').default}


Explanation :

Value from let image1require('./somRelativePath/image.jpg') is different with import calendarPic from './somRelativePath/image.jpg';

If you console them, value from calendarPic is a path, but if you use require, the value is an object like here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...