我正在获取包含用户个人资料图片路径的数据。我可以使用 gatsby-plugin-image 来渲染这个图像还是使用这个插件是不可能的?
具体来说,在 api 调用后,我得到这样返回的数据;
data:{
user:{
profilePicture: "https://mywebsite/img.jpg"
}
}
}
根据文档,使用 StaticImage 似乎不合适,因为我必须将 src 作为 Prop 传递(请参见下面的示例)。但是,使用 GatsbyImage(或 getSrc 或 getImage)返回 undefined 并且似乎也不是该插件的用途。是否有我遗漏的另一种模式,或者这个用例不是 gatsby-plugin-image 的正确使用?<StaticImage src={data.user.profilePicture} alt={data.user.fullname} />
返回:未找到图像“未定义”的数据
最佳答案
正如您在 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更多细节。
关于gatsby - 我可以将 gatsby-plugin-image 用于动态图像路径吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67175698/