使用 React 在 Gatsby 项目中显示目录的所有图片的最佳方式是什么?

What is the best way to display all pictures of a directory in a Gatsby project using React?

我正在使用 GatsbyJS starter https://www.gatsbyjs.org/starters/codebushi/gatsby-starter-forty/ 并且需要在页面上显示目录中的所有图片。 Gatsby 推荐的导入媒体的方法是使用 import 语句,但它会导致在构建后将哈希添加到文件名中。例如: /static/pic09-d59e4b49832baeb9c62a7a9d6c070f8c.jpg

如果我从目录中检索所有文件名并尝试使用 src={fileName} 创建 <img> 元素,它会生成空图像,因为文件名与服务器中已经具有哈希的文件名不匹配附加.

请推荐一个优雅的解决方案来解决这个问题。我的备份计划是将所有内容都放在不添加哈希的 static 目录中,但 Gatsby 文档不推荐这样做:https://www.gatsbyjs.org/docs/static-folder/

这是我现在拥有的:

import React from 'react'
import Layout from '../components/layout'

class Gallery extends React.Component {
    render() {
        const images = [];
        const req = require.context('../assets/images/signboards', false);
        req.keys().forEach(function (key) {
            images.push(key.substr(1));
        });
        return (
            <Layout>
                <div id="main">
                    <section className="spotlights">
                        <section>
                            {images.map((image) => {
                                return (
                                <div className="image">
                                <img src={'../assets/images/signboards' + image} alt="" />
                            </div>
                                )
                            })}
                        </section>
                    </section>
                </div>
            </Layout>
        )
    }
}

export default Gallery;

谢谢

注意:此答案假定您已经安装了 gatsby-source-filesystemgatsby-transformer-sharpgatsby-plugin-sharp


您可以使用 graphql 页面查询来获取特定文件夹中特定扩展名的所有文件,方法是使用正则表达式匹配器的组合进行过滤allFile

然后您可以遍历生成的边缘并使用 gatsby-image 显示图像。

import React from "react"
import { graphql } from "gatsby"
import Img from 'gatsby-image'

const IndexPage = ({data}) => (
  <>
    {data.allFile.edges.map(edge => {
      return <Img fluid={edge.node.childImageSharp.fluid} />
    })}
  </>
)

export default IndexPage

export const indexQuery = graphql`
  query AssetsPhotos {
    allFile(filter: {extension: {regex: "/(jpg)|(jpeg)|(png)/"}, dir: {regex: "/assets/images/signboards"}}) {
      edges {
        node {
          id
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
`

您可以使用 gatsby-source-filesystem 插件。 安装插件:

npm 安装 --save gatsby-source-filesystem

在 gatsby.config.js 中注册文件夹或其他过滤器(扩展名等)并为其命名。

{
  resolve: 'gatsby-source-filesystem',
  options: {
    path: `${__dirname}/src/pages/type1`,
    name: 'data',
  },
},

然后在组件中像这样构建查询:

{
allFile(filter: { sourceInstanceName: { eq: "data" } }) {
edges {
  node {
    extension
    dir
    modifiedTime
  }
} }}

您可以拥有许多这样的 "registrations" 提供不同的数据(文件夹、扩展名等)