如何使用gatsby-image查询多个图像?

时间:2019-06-04 04:05:36

标签: reactjs gatsby

我想将16张图像以网格格式渲染到网站上。

我正在使用以下插件:

  • gatsby-image
  • gatsby-source-filesystem
  • gatsby-plugin-sharp
  • gatsby-transformer-sharp

我阅读了文档,据我所知,它仅演示了如何查询一张图像。

例如

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

--- src

------图像

---------这16张图片

------页面

---------我要在其中渲染16张图像的页面

谢谢。

4 个答案:

答案 0 :(得分:4)

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

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="" />

答案 1 :(得分:1)

在GraphiQL中戳一下将对您,特别是Explorer有所帮助。尽管请记住,盖茨比片段在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的属性传递给gatsby-image

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

答案 2 :(得分:0)

这是一个带有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 name="logo.svg" alt="compony logo" />
or
<Image name="logo.png" alt="compony logo" />

答案 3 :(得分:0)

尽管当前存在问题,但16张图像全部位于images文件夹中,因此只需运行查询即可轻松获取所有可能的图像。像这样(可接受的答案):

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

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

因此,在这种情况下:(如果您在子文件夹中包含图片,例如在图片中有海滩,则可以采用这种方法)

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

如果要在视频中观看,这是个小的egghead clip

相关问题