繁体   English   中英

在前端读取包含大量图像的文件夹

[英]Reading folder containing a number of images on front-end

我是 React 的新手,我的产品在公共文件夹中包含多个图像。 文件夹名称是产品名称。

public
--product_1
--product_2
...
--product_n

每个文件夹内都有一些图像,不一定是相同的数字,文件名有1.jpg2.jpg等(字面意思是图像的文件名只是一个数字序列)。

所以,我有这个自定义的ProductCarousel组件(来自某个现有库的 Carousel 组件的包装器)实际上我想将每个文件夹的名称作为来自App (或任何父组件)的属性传递,并且该组件将简单地遍历它们所在的图像将显示在轮播中。

class ProductCarousel extends Component {

    constructor(props) {
        super(props);
        this.state = {
            productFolder: this.props.productFolder
        }
    }

    render() {
        return (
            <Carousel>
                { /* I'm doing a pseudo-code here somewhat, just correct me */ }
                {this.imagesInProductFolder.map(image =>
                        <div key={`${this.state.productFolder} + '_' + image`} >
                            <img alt={`${this.state.productFolder} + '_' + image`} src={`${this.state.productFolder} + '/' + image`} />
                        </div>
                    )
                }
            </Carousel>
        );
    }
}

我的问题:

  1. 这可以用纯 JavaScript 完成吗?

  2. 如果使用纯 JavaScript 太困难​​(或不可能)或代码行太多,是否有可用的 React 库以更简单的方式解决?

  3. 如果上述答案是否定的,是否有必要使用像 NodeJS 这样的服务器端语言(我的最后手段,我猜混合服务器端和客户端是“不好的”)?

对于这三个中的任何一个,任何示例操作代码都将受到赞赏。

是的,它可以做到。 添加componentdidmounttryRequire函数将解决问题。

componentdidmount我们将在每个文件夹中迭代并导入图像并将它们保存在状态中。 tryRequire函数检查特定图像是否存在于该文件夹中。 如果结果为false,则会中断componentdidmount的迭代

componentDidMount() {
    let i = 1;
    const pathName = this.props.fileName;

    while (this.tryRequire(`./images/${pathName}/${i}.jpg`)) {
      import(`./images/${pathName}/${i}.jpg`).then(image => {
        this.setState({ images: [...this.state.images, image.default] });
      });
      i = i + 1;
    }
  }
  tryRequire(path) {
    try {
      return require(`${path}`);
    } catch (err) {
      return null;
    }
  }

更新

实际上,如果您将图像保存在与组件相同的文件夹或子文件夹中,则此方法将起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM