问题描述
我正在尝试使 gatsby-background-image 与 gatsby-plugin-image 的 v3 一起工作。我遵循了文档,发现我应该使用 gbimage-bridge。
出于某种原因,它似乎不起作用。在 ide 中测试时,我的查询工作正常。我试图以各种方式更改我的查询和常量,但似乎无法使其正常工作。
我的代码:
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
游乐场中对其进行测试