javascript - 如何在反应中显示图像文件夹中的每个图像
问题描述
我的create-react-app
项目中有一个包含一堆图像的图像文件夹。我想显示组件中的每一个图像。
├── Components
│ ├── Icons
│ │ ├── Icon.jsx (I want to display every single icon)
│
│
├── Images
│ ├── Icons
│ │ ├── ... (over 100 SVG icons)
在我的 .jsx 文件中,我想遍历每个图像/图标并显示它。
图标.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
or SVG
s 并显示它。以下是我遵循的过程:
文件夹结构
-public
-src
|-component
|-images
|-1.png
|-2.png
|-3.png
.
.
|-some x number.png
在component
你想在那里消费的image
地方,你必须这样做:
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>
)
}
}
它对我有用;试试看。
推荐阅读
- google-analytics - 如何使用计算字段拆分 Google Data Studio 中的事件值
- r - 多行图例文本,包括带有 ggplot 的指数
- javascript - 未从 Angular 中的功能接收产品
- jquery - 如何通过在 .animate 方法中设置相同的速度来禁用平滑动画
- java - 更改项目视图中的背景颜色效果
- angular - 从Angular2中的AppComponent将参数传递给子组件或对等组件
- jquery - 如何扩展和添加到 .NET Core 中的 IFormFile 接口。提交ajax请求时需要向序列化数组追加数据
- c - 无法在命名管道中写入
- logging - 如何从 Elastic Beanstalk 中清除旧日志文件?
- html - 列间距/填充