Importing multiple files in react

前端 未结 5 894
滥情空心
滥情空心 2020-12-24 07:01

I am using create-react-app for my react project. It has got webpack configured for importing images. I wish to import multiple images (say 10) from a images folder into a c

5条回答
  •  轮回少年
    2020-12-24 07:51

    A some kind of mixed approach to the above answers, which is maybe more clear, at least for me is:

    1. inside the folder (e.g. in /src/components/app/assets/png/icons) with many many images we create a file: "index.js" with content like:

       export const file1 = require("./IconRed_100x100.png");
       export const file2 = require("./IconSilver_100x100.png");
       export const file3 = require("./IconWhite_100x100.png");
       export const file4 = require("./IconBrown1_100x100.png");
       export const file5 = require("./IconBrown2_100x100.png");
       export const file6 = require("./IconGray_100x100.png");
       export const file7 = require("./IconMetallic_100x100.png");
       export const file8 = require("./IconMetallic_100x100.png");
       export const file9 = require("./IconMetallic_100x100.png");
       export const file10 = require("./IconMetallic_100x100.png");
       ...
      

    (we can create this file outside of our app via a python script else it would make no sense to use this approach at all, as we can then implement multiple import-lines inside of the react-component where we need the images; sure we need to know WHAT and HOW many files we want to import)

    1. inside the component where we need these images (here it´s called ImageGallery inside /src/components/app/imageGallery/):

       import * as ALL from "../assets/png/icons";
      
       const itemsToRender = [];
       for (let x in ALL) {
        console.log(x);
        itemsToRender.push(
          
      ); } function ImageGallery() { return ( <>
      {itemsToRender}
      ); } export default ImageGallery;

    Then we rendered all the images from "/src/components/app/assets/png/icons" inside our React-component called ImageGallery.

提交回复
热议问题