我的第一个建议是在开发时始终使用 GraphiQL 页面。它让您了解如何在组件上使用查询结果。
http://localhost:8000/___graphql
您的查询取决于您希望如何显示您的图像。
假设您在 Contentful 上的 Asset 内容模型上存储了字段名称为 myImage 的图像。
使用 HTML5 <img /> 标签显示
如果你想使用简单的<img />标签
您的查询
contentfulAsset(title: { eq: "kevin"}}) {
title
file {
url
}
}
你的组件
// ...
const MyComponent = props => {
const myImage = props.data.contentfulAsset;
return <img src={myImage.file.url} alt={myImage.title} />
}
用 gatsby-image 插件显示
如果您想利用 gatsby-image 插件,您首先需要知道是否要在查询中使用 resolutions 或 sizes 子项。
更多信息请参见gatsby-image documentation。
然后您可以使用gatsby-source-contentful 提供的查询Fragment。
见https://www.gatsbyjs.org/packages/gatsby-image/#gatsby-source-contentful
您的查询
假设我们想在加载时显示具有模糊效果的响应式图像,格式为Webp:
contentfulAsset(title: { eq: "kevin"}}) {
title
sizes(quality: 100) {
...GatsbyContentfulSizes_withWebp
}
}
注意:默认情况下,resolutions 和 sizes 质量设置为 50。这就是我在此查询中将其设置为 100 的原因
你的组件
const MyComponent = props => {
const myImage = props.data.contentfulAsset;
return <Img sizes={myImage.sizes} alt={myImage.title} />
}
像大多数官方 Gatsby 插件一样,您可以在 GitHub 存储库的 examples 文件夹中找到一个非常好的示例:
https://github.com/gatsbyjs/gatsby/tree/master/examples/using-contentful