【问题标题】:Gatsby / Graphql - Can't display img from queryGatsby / Graphql - 无法从查询中显示 img
【发布时间】:2020-10-22 09:17:30
【问题描述】:

下面是我的代码:

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


const ImageGallery = () => {


const data = useStaticQuery(graphql`
query {
  images: allFile(filter: { sourceInstanceName: {eq: "images" }}) {
    edges {
      node {
        relativePath
        childImageSharp {
          id
          fluid {
            originalImg
          }
        }
      }
    }
  }
}
`)

 // Filters all the images from "gallery-one"

 const galleryImages = data.images.edges.filter(edge => 
  edge.node.relativePath.startsWith("gallery-one")
 )

console.log(data)
console.log(galleryImages)


    return (
        <div>
            <h1>Gallery One</h1>
            {
             // Mapping over galleryImages array to display each image

              galleryImages.map((image) =>
                <div>
                // Returns relative path for each image
                {image.node.childImageSharp.fluid.originalImg}
                 // Returns nothing
                <Img fluid={image.node.childImageSharp.fluid.originalImg} />
                </div>
              )
            }
        </div>
    )
}


export default ImageGallery

随着地图的第一部分,它返回:

/static/3608211e3ce3f78486c9e344b92332d9/5f7bf/20171107_155145.jpg

/static/fccd9cdb1c9b525bfaf9282343d680a6/5f7bf/20171101_103124.jpg

/static/cdcbaebc030e210debc70bdff7a8d539/5f7bf/20171107_155126.jpg

/static/ef8708d7f536bd152c9ce98833d6d871/5f7bf/20171101_103218.jpg

/static/1c3b4e40cb5044e604009935b625fa38/5f7bf/20171101_103138.jpg

'gallery-one' 文件夹中的每个图像一个,但我不知道如何使用 Gatsby Img 显示它。

我觉得这很接近,但我似乎无法弄清楚

fluid={image.node.childImageSharp.fluid.originalImg}

【问题讨论】:

    标签: reactjs graphql gatsby


    【解决方案1】:

    是的,你快到了。

    当您使用 gatsby-image 查询要显示的图像时,您有 2 个选项:

    • 使用 GraphQL 片段:

      您应该使用...GatsbyImageSharpFluid 而不是使用originalImg,这将为fluid 对象提供所需的所有信息。

    • 查询所有需要的数据。在这种情况下,您应该使用:

        fluid (maxWidth: 800) {
          aspectRatio
          src
          srcSet
          sizes
          originalImg
          originalName
        }
      

      免责声明:默认maxWidth800px。如果不设置,则取默认值。

    收集完所有信息后,需要将其传递给&lt;Img&gt;,删除您的originalImg,例如:

    fluid={image.node.childImageSharp.fluid}
    

    更多信息请查看Gatsby Image API documentation

    【讨论】:

      猜你喜欢
      • 2019-10-26
      • 1970-01-01
      • 2020-03-23
      • 2021-05-04
      • 2021-07-03
      • 1970-01-01
      • 2019-11-22
      • 2019-04-02
      • 2021-11-13
      相关资源
      最近更新 更多