微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

gatsby-image-background 使用 v3 gatsby-image

如何解决gatsby-image-background 使用 v3 gatsby-image

我正在尝试使 gatsby-background-image 与 gatsby-plugin-image 的 v3 一起工作。我遵循了文档,发现我应该使用 gbimage-bridge。

出于某种原因,它似乎不起作用。在 ide 中测试时,我的查询工作正常。我试图以各种方式更改我的查询和常量,但似乎无法使其正常工作。

现在它只输出文本 Test 但没有显示背景。

我的代码

import { graphql,useStaticQuery } from "gatsby"
import { getimage } from "gatsby-plugin-image"
import { BgImage } from "gbimage-bridge"

const GbiBridged = () => {
  const { backgroundImage123 } = useStaticQuery(graphql`
    query {
      backgroundImage123: allWpPage {
        nodes {
          ACFforside {
            heroimg {
              localFile {
                childImageSharp {
                  gatsbyImageData(
                    width: 2000
                    quality: 50
                    placeholder: BLURRED
                    formats: [AUTO,WEBP,AVIF]
                  )
                }
              }
            }
          }
        }
      }
    }
  `)

  const pluginImage = getimage(backgroundImage123)

  return (
        <BgImage image={pluginImage}>Test</BgImage>
  )
}

export default GbiBridged

解决方法

我认为您的代码段应如下所示:

import React from 'react'
import { graphql,useStaticQuery } from 'gatsby'
import { getImage,GatsbyImage } from "gatsby-plugin-image"

import { convertToBgImage } from "gbimage-bridge"
import BackgroundImage from 'gatsby-background-image'

const GbiBridged = () => {
  const { backgroundImage123 } = useStaticQuery(
    graphql`
      query {
        backgroundImage123: allWpPage {
          nodes {
           ACFforside {
             heroimg {
               localFile {
                 childImageSharp {
                   gatsbyImageData(
                     width: 2000
                     quality: 50
                     placeholder: BLURRED
                     formats: [AUTO,WEBP,AVIF]
                   )
                 }
               }
             }
           }
         }
       }
     }
    `
  )
  const image = getImage(backgroundImage123.nodes[0].ACFforside.heroimg.localFile)

  // Use like this:
  const bgImage = convertToBgImage(image)

  return (
    <BackgroundImage
      Tag="section"
      // Spread bgImage into BackgroundImage:
      {...bgImage}
      preserveStackingContext
    >
      <div style={{minHeight: 1000,minWidth: 1000}}>
        <GatsbyImage image={image} alt={"testimage"}/>
      </div>
    </BackgroundImage>
  )
}
export default GbiBridged

我假设您的查询正在获取正确的节点,否则,请在 localhost:8000/___graphql 游乐场中对其进行测试

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。