在React中导入多个文件 [英] Importing multiple files in react
问题描述
我在我的React项目中使用create-react-app。它已将webpack配置为导入图像。我希望将多个图像(例如10个)从图像文件夹导入到组件中。最简单的方法是添加多个import语句,例如-
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 component. The easiest way of doing this would be to add multiple import statement such as -
import Img0 from '../images/0.png';
import Img1 from '../images/1.png';
import Img2 from '../images/2.png';
import Img3 from '../images/3.png';
import Img4 from '../images/4.png';
import Img5 from '../images/5.png';
import Img6 from '../images/6.png';
...
当我们有多个文件时,上面的代码不是一个好的选择导入。有没有办法在循环中添加导入语句?我尝试添加for循环,但无法修改变量Img0,Img1等(使用ES6``不能将变量转换为字符串)
The above code would not be a good choice when we have multiple files to import. Is there a way to add the import statements in a loop? I tried adding for loop but I was unable to modify the variables Img0, Img1 etc. (using ES6 `` didn't work as it converted the variable to a string)
推荐答案
您不能使用单个import语句,但是您可以这样做:
You can't use a single import statement, but you can do this:
function importAll(r) {
let images = {};
r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
return images;
}
const images = importAll(require.context('./images', false, '/\.png/'));
<img src={images['0.png']} />
来源。
这篇关于在React中导入多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!