如何使用 gatsby-image 查询多张图片?

How do I query multiple images with gatsby-image?

我有 16 张图像要以网格格式呈现到网站上。

我为此使用了以下插件:

我看了文档,据我所知,它只演示了如何查询一张图片。

例如

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

export default ({ data }) => (
  <div>
    <h1>Hello gatsby-image</h1>
    <Img fixed={data.file.childImageSharp.fixed} />
  </div>
)

export const query = graphql`
  query {
    file(relativePath: { eq: "blog/avatars/kyle-mathews.jpeg" }) {
      childImageSharp {
        # Specify the image processing specifications right in the query.
        # Makes it trivial to update as your page's design changes.
        fixed(width: 125, height: 125) {
          ...GatsbyImageSharpFixed
        }
      }
    }
  }
`

但是如果我有 16 张图片,我该如何处理呢?单独写 16 个查询看起来很麻烦,以后很难阅读。

我在文档中看到这段代码引用了多个图像,但我在尝试访问图像本身时遇到了问题。

例如

export const squareImage = graphql`
  fragment squareImage on File {
    childImageSharp {
      fluid(maxWidth: 200, maxHeight: 200) {
        ...GatsbyImageSharpFluid
      }
    }
  }
`

export const query = graphql`
  query {
    image1: file(relativePath: { eq: "images/image1.jpg" }) {
      ...squareImage
    }

    image2: file(relativePath: { eq: "images/image2.jpg" }) {
      ...squareImage
    }

    image3: file(relativePath: { eq: "images/image3.jpg" }) {
      ...squareImage
    }
  }
`

我的文件夹结构如下:

---package.json

---来源

------图片

------------第16张图片

------页数

------------我要渲染

中的16张图片的页面

等等

谢谢。

浏览一下 GraphiQL 应该会对您有所帮助,尤其是资源管理器。尽管请记住,Gatsby 片段在 GraphiQL 中不起作用。

{
  allImageSharp {
    edges {
      node {
        id
        fluid(maxWidth: 200, maxHeight: 200) {
            ...GatsbyImageSharpFluid
        }
      }
    }
  }
}

所以上面的内容应该等于下面的查询,在 GraphiQL

中工作
{
  allImageSharp {
    edges {
      node {
        id
        fluid(maxHeight: 200, maxWidth: 200) {
          src
          srcSet
          base64
          aspectRatio
          originalImg
          sizes        
        }
      }
    }
  }
}

然后您的组件可以使用相同的查询并呈现如下结果:

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

const imgGridStyle = {
  display: 'grid',
  gridTemplateColumns: `repeat(auto-fill, 200px)`
};

export default ({ data }) => (
  <div>
    <h1>Hello gatsby-image</h1>
    <div style={imgGridStyle}>
      {data.allImageSharp.edges.map(edge => 
        <Img fluid={edge.node.fluid} />
      )}
    </div>
  </div>
)

export const query = graphql`
  query {
    allImageSharp {
      edges {
        node {
          id
          fluid(maxWidth: 200, maxHeight: 200) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  }
`

您可以轻松遍历从 data.allImageSharp.edges.map 中的查询返回的 imageSharp 节点结果数组。然后将每个节点的 fluid 属性 作为 fluid prop 传递给 gatsby-image.

注意:这会呈现项目中的 每个 imageSharp 节点,这可能是也可能不是您想要实现的。


要按文件夹名称过滤查询,您可以这样调整查询:

{
  allImageSharp(filter: {fileAbsolutePath: {regex: "/(myFolder)/"  }}) {
    edges {
      node {
        id
        fluid(maxWidth: 200, maxHeight: 200) {
            ...GatsbyImageSharpFluid
        }
      }
    }
  }
}

查看 gatsby graphql reference for filter 了解如何对查询执行其他类型的过滤器。

从 Gatsby v3 你只需要使用 gatsby-plugin-image 插件,提供自动图像优化

import { StaticImage } from "gatsby-plugin-image"
export function Dino() {
  return (
    <StaticImage
      src="../images/dino.png"
      alt="A dinosaur"
      placeholder="blurred"
      layout="fixed"
      width={200}
      height={200}
    />
  )
}

更多信息: https://www.gatsbyjs.com/docs/how-to/images-and-media/using-gatsby-plugin-image

Gatsby v2:

最简单的方法是创建图像提供程序:

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

const Image = ({ fileName, alt, style }) => {
  const { allImageSharp } = useStaticQuery(graphql`
    query {
      allImageSharp {
        nodes {
          fluid(maxWidth: 1600) {
            originalName
            ...GatsbyImageSharpFluid_withWebp
          }
        }
      }
    }
  `)

  const fluid = allImageSharp.nodes.find(n => n.fluid.originalName === fileName)
    .fluid

  return (
    <figure>
      <Img fluid={fluid} alt={alt} style={style} />
    </figure>
  )
}

export default Image;

然后,导入后,轻松插入你需要的图片:

<Image fileName="yourImage.jpg" style={{ width: '100%' }} alt="" />

这是一个支持 TypeScript 和 SVG 的简单示例:

更新gatsby-config.js

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/assets/images`,
      },
    },
  ],
};

创建图像组件

import * as React from 'react';
import { FC } from 'react';
import { graphql, StaticQuery } from 'gatsby';
import Img from 'gatsby-image';

interface IProps {
  name: string;
  alt: string;
  className?: string;
}

const Image: FC<IProps> = ({ name, alt, className }) => (
  <StaticQuery
    query={graphql`
      query AllImages {
        allImagesWithoutSVGExtension: allFile(
          filter: {
            sourceInstanceName: { eq: "images" }
            extension: { regex: "/jpeg|jpg|png|gif/" }
          }
        ) {
          nodes {
            publicURL
            extension
            sharp: childImageSharp {
              fluid {
                originalName
                ...GatsbyImageSharpFluid_withWebp
              }
            }
          }
        }
        allImagesWithSVGExtension: allFile(
          filter: {
            sourceInstanceName: { eq: "images" }
            extension: { eq: "svg" }
          }
        ) {
          nodes {
            publicURL
            extension
          }
        }
      }
    `}
    render={({ allImagesWithoutSVGExtension, allImagesWithSVGExtension }) => {
      const isNameWithSVGExtension = name.indexOf('svg') !== -1;

      const renderImageWithSVGExtension = () => {
        const image = allImagesWithSVGExtension.nodes.find(
          ({ publicURL }) => publicURL && publicURL.indexOf(name) !== -1
        );
        return image ? (
          <img
            className={className}
            src={image.publicURL}
            alt={alt}
            width={100}
            height={100}
          />
        ) : null;
      };

      const renderImageWithoutSVGExtension = () => {
        const image = allImagesWithoutSVGExtension.nodes.find(
          ({ publicURL }) => publicURL && publicURL.indexOf(name) !== -1
        );
        return image && image.sharp && image.sharp.fluid ? (
          <Img className={className} fluid={image.sharp.fluid} alt={alt} />
        ) : null;
      };

      return isNameWithSVGExtension
        ? renderImageWithSVGExtension()
        : renderImageWithoutSVGExtension();
    }}
  />
);

export { Image };

使用Image组件作为

<Image name="logo.svg" alt="compony logo" />
or
<Image name="logo.png" alt="compony logo" />

尽管当前问题的情况是,所有 16 张图像都在 images 文件夹中,然后只需 运行 查询即可轻松获取所有可能的图像。像这样(接受的答案):

{
  allImageSharp {
    edges {
      node {
        id
        fluid(maxWidth: 200, maxHeight: 200) {
            ...GatsbyImageSharpFluid
        }
      }
    }
  }
}

但在大多数情况下,您希望图像文件夹中有子文件夹,以便根据需要排列图像。 (至少那是我的情况)。

所以在那种情况下:(如果你在子文件夹中有图像,假设 beachimages 中,你可以采用这种方法)

export const query = graphql`
  query {
    allFile(filter: { relativeDirectory: { eq: "beach" } }) {
      edges {
        node {
          id
          childImageSharp {
            fluid {
              ...GatsbyImageSharpFluid_withWebp
            }
          }
        }
      }
    }
  }
`

如果您想在视频中看到,这是一个小egghead clip