首页 > 解决方案 > 如何在反应中显示图像文件夹中的每个图像

问题描述

我的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
    );
  }
}

标签: javascriptreactjsloopsjsx

解决方案


我有同样的情况,我必须从文件夹中选择imagesor SVGs 并显示它。以下是我遵循的过程:

文件夹结构

  -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>
        )
    }
}

它对我有用;试试看。


推荐阅读