简体   繁体   中英

Show images <img src='path' /> in React, has some issues

I'm creating a template front-page in React and I need to show many local-dummy images .

Inside my <Main /> component I import other components which pass the image path as a parameter, like so:

  <Container
    type="image"
    source=...
    message=""
    link="" />

As I have searched and read on different answers, so far in React we can't just use <img src="relative image path" /> , I don't know exactly what is the issue, cache thing / render thing etc.

What I've done so far in order to load the images on page:
1. First importing them on the top: import img1 from '../assets/img/hd1080.png'
2. Pass the image to the component like so:

<Container
    type="image"
    source={img1}
    message=""
    link="" />
  1. Inside , I pass it to the img like so: <img src={img1} />

Just wondering if there is a faster way, that does not need to first importing the images and then using them, src="relative path"

In React you can also use the relative path of an image as well.

However, considering your question, you probably have Webpack compiling and bundling your assets. "The Webpack Way" prefers to have the compilation of everything handled by Webpack. This has some merits such as being able to optimize and inline images via Webpack plugins.

Another approach would be to compile your JS & CSS with Webpack but copy the images as-is to the "compiled folder".

Webpack's development server lets you do this if you want, and sometimes it's easier and makes more sense than having the JS files import the images.

If your only goal is simplicity, then it's simpler to import - you don't need another "file copier" script for your file compilation, and Webpack can compress or inline your images.

However, if importing every image becomes tedious to manage, consider making a simple file copy rule (with Makefiles for example), copying the files to the dist folder and simply writing <Container source="/images/x.png"> .

If you are dealing with multiple files then i would suggest you to make a separate file in and import all your images their. For exp :

module.exports = {
    Slider_Arrow_Icon: {
       back_Arrow_Icon: require('../images/arrow-slide-back')
    }

}

And then import this file and you can use easily. If any query lmk.

Hope this find useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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