我在Gatsby中使用Strapi,在动态区域内渲染图像时遇到困难。我正在使用:
- 背带3.6.2
- 盖茨比3.5.1
- gatsby源代码strapi 1.0.0
- gatsby插件镜像1.5.0
- gatsby插件sharp 3.5.0
- gatsby变压器夏普3.5.0
GraphQL可以很容易地查询直接在集合类型中找到的顶级图像字段,以返回gatsbyImageData
,例如缩略图字段:
query MyQuery {
allStrapiPage {
nodes {
Title
Body
thumbnail {
localFile {
childImageSharp {
gatsbyImageData
}
}
}
}
}
}
然而,在上面的查询中,Body
是一个具有数十个可选组件的动态区域字段,其中许多组件包含图像字段。为Body返回的数据是标准的JSON数据,这意味着图像字段没有所需的gatsbyImageData
,请参阅示例响应:
"Body": [
{
"PrimaryImage": {
"id": 12,
"name": "Test Image",
"alternativeText": "",
"caption": "",
"width": 338,
"height": 260,
"formats": {
"thumbnail": {
"name": "thumbnail_Test Image",
"hash": "thumbnail_testimage_c3ced5807d",
"ext": ".png",
"mime": "image/png",
"width": 203,
"height": 156,
"size": 78.25,
"path": null,
"url": "/uploads/thumbnail_testimage_c3ced5807d.png"
}
},
"hash": "testimage_c3ced5807d",
"ext": ".png",
"mime": "image/png",
"size": 154.53,
"url": "/uploads/testimage_c3ced5807d.png",
"previewUrl": null,
"provider": "local",
"provider_metadata": null,
"created_at": "2021-04-19T14:20:38.086Z",
"updated_at": "2021-04-19T14:20:38.133Z",
"localFile___NODE": "c5a14269-31a2-505a-b2ff-8251e6ca5051"
},
"strapi_component": "sections.task-row"
}
}]
<StaticImage />
不接受动态src
,所以我不能使用url
字段。我必须使用<GatsbyImage/>
,它需要gatsbyImageData
对象。
是否有任何方法可以修改查询或使用可用于获得<GatsbyImage />
渲染图像的字段
更新:一位Strapi开发人员已经确认,目前这是不可能的。不幸的是,我目前最好的解决方案是不使用gatsby-plugin-image
,而是使用<img src={imagepath} />
其中CCD_ 12通过Strapi的运行实例直接引用图像。http://localhost:1337/uploads/test-image.png
或者,您可以将从Strapi文件夹到Gatsby文件夹的图像复制到构建过程中,这样,如果您希望将环境分开,就可以在Gatsby本地引用它们(对于许多图像可能较慢(
仍希望有更好的解决方案:(
对于Strapi中的动态区域,我们需要使用扩散运算符(…(,然后在上使用__typename组件
例如:
DynamicZoneName{
...on ComponentName{
// component values
}
...on AnotherComponentName{
// component values
}
}
在您的情况下,新查询应该类似于:
query MyQuery {
allStrapiPage {
nodes {
Title
Body{
... on ComponentPrimaryImage{
formats,
url,
name,
id,
//any other values you want
}
}
thumbnail {
localFile {
childImageSharp {
gatsbyImageData
}
}
}
}
}
}
步骤
为strapi应用程序打开Graphql url。
编写您的旧查询
在动态区域的括号内写入
... on
打开自动完成链接动态区域的__typename
参考初始代码块继续
请参阅本文以了解graphql中的动态区域实现