Load local images in React.js

后端 未结 10 2089
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 23:08

I have installed React using create-react-app. It installed fine, but I am trying to load an image in one of my components (Header.js, file path: <

10条回答
  •  眼角桃花
    2020-11-30 23:28

    If you have questions about creating React App I encourage you to read its User Guide.
    It answers this and many other questions you may have.

    Specifically, to include a local image you have two options:

    1. Use imports:

      // Assuming logo.png is in the same folder as JS file
      import logo from './logo.png';
      
      // ...later
      logo
      

    This approach is great because all assets are handled by the build system and will get filenames with hashes in the production build. You’ll also get an error if the file is moved or deleted.

    The downside is it can get cumbersome if you have hundreds of images because you can’t have arbitrary import paths.

    1. Use the public folder:

      // Assuming logo.png is in public/ folder of your project
      logo
      

    This approach is generally not recommended, but it is great if you have hundreds of images and importing them one by one is too much hassle. The downside is that you have to think about cache busting and watch out for moved or deleted files yourself.

    Hope this helps!

提交回复
热议问题