如何在React中显示图像文件夹中的每个图像 [英] How to display every image inside an image folder in react
本文介绍了如何在React中显示图像文件夹中的每个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的create-react-app
项目中有一个包含一堆图像的图像文件夹.我想在组件中显示每个图像.
I have an image folder in my create-react-app
project with a bunch of images. I want to display every single image in the components.
├── Components
│ ├── Icons
│ │ ├── Icon.jsx (I want to display every single icon)
│
│
├── Images
│ ├── Icons
│ │ ├── ... (over 100 SVG icons)
在我的.jsx文件中,我想遍历每个图像/图标并显示它.
In my .jsx file, I want to loop over every image/icon and display it.
Icons.jsx
import React, { Component } from 'react';
import Icons from '../../Images/Icons';
class Icons extends Component {
render() {
return (
//Loop over every icon and display it
);
}
}
推荐答案
在相同的情况下,我必须从文件夹中选择images
或SVG
s并显示它.以下是我遵循的过程:
I had the same scenario where I have to pick images
or SVG
s from the folder and display it. Below is the process I followed :
文件夹结构
-public
-src
|-component
|-images
|-1.png
|-2.png
|-3.png
.
.
|-some x number.png
在component
中您想在那里消费image
的任何地方,您都必须这样做:
In component
where ever you want to consume the image
there, you have to do this:
export default App;
import React from 'react';
import ReactDOM from 'react-dom';
var listOfImages =[];
class App extends React.Component{
importAll(r) {
return r.keys().map(r);
}
componentWillMount() {
listOfImages = this.importAll(require.context('./images/', false, /\.(png|jpe?g|svg)$/));
}
render(){
return(
<div>
{
listOfImages.map(
(image, index) => <img key={index} src={image} alt="info"></img>
)
}
</div>
)
}
}
它为我工作;试试看.
这篇关于如何在React中显示图像文件夹中的每个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文