【问题标题】:Best way to loop images in react在反应中循环图像的最佳方法
【发布时间】:2021-01-27 04:27:28
【问题描述】:

我使用 create-react-app 创建了一个项目,并且在源代码中有一个名为 images 的文件夹。 我想在图像文件夹中循环并显示它们。

到目前为止,我的代码如下所示:

import React, { Component } from 'react'
import images from './images/wd/'

const listOfImages = []

class Myloop extends Component {
  importAll(r) {
    return r.keys().map(r)
  }

  componentWillMount() {
    listOfImages = this.importAll(require.context(images, false, /\.(png)$/))
  }

  render() {
    return (
      <>
        <ul>
          <li>
            {listOfImages.map((images, index) => (
              <img src={images} key={index} alt="info"></img>
            ))}
          </li>
        </ul>
      </>
    )
  }
}

export default Myloop

保存文件后,我在终端上显示以下消息:

找不到模块:无法解析“./images/wd/” '/mywebsite/src/components'

我不确定出了什么问题,但任何帮助都会很棒。

【问题讨论】:

  • require.context(images 应该是require.context('./images/wd/'
  • @Dominik。我已经尝试了许多这些方法,但根本没有用。最新版本中没有 webpack.config.js。
  • @cbr,路径原来如你所描述,但即便如此,在'/mywebsite/src/中出现“Module not found: Can't resolve './images/wd/'的错误组件”仍然存在。
  • 图片路径中的“/wd/”是什么?

标签: javascript reactjs


【解决方案1】:

这里是正确答案Dynamically import images from a directory using webpack 你不能只用“import”同时导入整个目录

    function importAll(r) {
      return r.keys().map(r);
    }
    
    const images = importAll(
      require.context("./images/wd", false, /\.(png|jpe?g|svg)$/)
    );

UPD:因此,在您的情况下,删除 import,将 images 与 url 交换并将 listOfImages 添加到状态

import React, { Component } from "react";

class Myloop extends Component {
  constructor(props) {
    super(props);
    this.state = { listOfImages: [] };
  }
  importAll(r) {
    return r.keys().map(r);
  }

  componentWillMount() {
    const list = this.importAll(
      require.context("./images/wd", false, /\.(png)$/)
    );
    this.setState({
      listOfImages: list
    });
  }

  render() {
    return (
      <>
        <ul>
          <li>
            {this.state.listOfImages.map((image, index) => (
              <img src={image} key={index} alt="info"></img>
            ))}
          </li>
        </ul>
      </>
    );
  }
}

export default Myloop;

【讨论】:

  • 那是正确的。谢谢@Julka。我实现了,它就像一个魅力。
  • 虽然,如果我的图像文件夹在组件文件夹之外,它不会加载。有什么想法吗?
  • @ffas,将路径从“./images/wd”更改为需要
猜你喜欢
  • 2020-04-02
  • 1970-01-01
  • 2018-01-09
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 2011-04-01
  • 2021-06-18
相关资源
最近更新 更多