我可以将 gatsby-plugin-image 用于动态图像路径吗?

Can I use gatsby-plugin-image for a dynamic image path?

我正在获取包含用户个人资料图片路径的数据。我可以使用 gatsby-plugin-image 来渲染这个图像还是不能使用这个插件?

具体来说,在 api 调用之后,我得到了这样返回的数据;

data:{
 user:{
  profilePicture: "https://mywebsite/img.jpg"
     }
    }
   }

根据文档,使用 StaticImage 似乎不合适,因为我必须将 src 作为道具传递(请参见下面的示例)。但是,使用 GatsbyImage(或 getSrc 或 getImage)returns 未定义,而且似乎也不是该插件的预期用途。我是否遗漏了另一种模式,或者这个用例是否没有正确使用 gatsby-plugin-image?

<StaticImage src={data.user.profilePicture} alt={data.user.fullname} />

returns: 未找到图像“未定义”的数据

如您在 Gatsby image documentation 中所见,StaticImage 组件无法接收外部 props。所以这会起作用:

 <StaticImage src="https://mywebsite/img.jpg" alt="" />

但这不会:

 <StaticImage src={data.user.profilePicture} alt="" />

这是因为 Gatsby 会在构建时下载图像。

要使用 GatsbyImage(创建动态图像),您需要将图像存储在本地并通过文件系统告诉 Gatsby,它们位于何处以允许 Gatsby 使用它的转换器和锐化到该图像,什么将创建一个可查询的 GraphQL 节点。这将允许您像这样查询它们:

import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"

function BlogPost({ data }) {
 const image = getImage(data.blogPost.avatar)
 return (
   <section>
     <h2>{data.blogPost.title}</h2>
     <GatsbyImage image={image} alt={data.blogPost.author} />
     <p>{data.blogPost.body}</p>
   </section>
 )
}

export const pageQuery = graphql`
 query {
   blogPost(id: { eq: $Id }) {
     title
     body
     author
     avatar {
       childImageSharp {
         gatsbyImageData(
           width: 200
           placeholder: BLURRED
           formats: [AUTO, WEBP, AVIF]
         )
       }
     }
   }
 }
`

您可以查看 https://www.gatsbyjs.com/plugins/gatsby-plugin-image/#dynamic-images 了解更多详情。