【问题标题】:How do I use GraphQL to query an image from Contentful?如何使用 GraphQL 从 Contentful 中查询图像?
【发布时间】:2022-01-20 18:26:03
【问题描述】:

我正在使用 Gatsby 构建一个基本站点,并将其连接到 Contentful。我将 2 个资产上传到 Contentful:

第一个资产如下所示:

除了标题是 test-two 之外,第二个资产 100% 相同。

如果我使用 about 查询并将 URL 传递到 img 标签中,我的图像将显示。但是,我正在尝试使用 GatsbyImage,但似乎无法找出问题所在。

我一直在尝试遵循 this 教程并使用,但我无法得到任何渲染。我的查询需要如何更改才能使用 gatsby-image?

【问题讨论】:

    标签: reactjs gatsby contentful gatsby-image


    【解决方案1】:

    在这种情况下,您正在查询urlfilenamecontentType。为了能够使用GatsbyImage,您需要查询从 Gatsby 创建的节点(即gatsbyImageData),它应该包含在 Contentful 资产节点的名称中。比如:

    {
      allContentfulAsset {
        edges {
          node {
            test {
              title
              gatsbyImageData(layout: CONSTRAINED)
            }
          }
        }
      }
    }
    

    在 GraphiQL 游乐场 (localhost:8000/___graphql) 中检查创建的节点。

    完成后,在您的组件中,您应该能够执行以下操作:

    import { graphql } from "gatsby"
    import { GatsbyImage, getImage } from "gatsby-plugin-image"
    
    function SomePage({ data }) {
      const image = getImage(data.allContentfulAsset.test)
      return (
        <section>
          <GatsbyImage image={image} alt={`Some alt text`} />
        </section>
      )
    }
    
    export const pageQuery = graphql`
      query {
          allContentfulAsset {
            edges {
              node {
                test {
                  title
                  gatsbyImageData(layout: CONSTRAINED)
               }
             }
           }
         }
      }
    `
    

    如果节点没有出现,请检查gatsby-config.js 文件中的配置。


    ⚠️ 免责声明

    注意,您尝试使用的教程是使用 gatsby-image(从 Gatsby v2 向后),其中渲染的组件是 Img,在您使用 gatsby-image 时从 gatsby-image 导入(来自 Gatsby v3之后),从gatsby-plugin-image 导入。第一个已弃用,查询结构略有不同。正如您在分享的指南顶部看到的那样:

    gatsby-image 包现已弃用。新的Gatsby image plugin 具有更好的性能、酷炫的新功能和更简单的 API。请参阅migration guide 了解如何升级。

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 2020-10-25
      • 2021-03-24
      • 2019-09-26
      • 2020-06-28
      • 2018-08-13
      • 2020-02-03
      • 2021-04-13
      • 2018-06-16
      相关资源
      最近更新 更多