gpt4 book ai didi

reactjs - 如何使用 Gatsby 从 Contentful Rich Text 字段中调用和使用嵌入式 Assets ?

转载 作者:行者123 更新时间:2023-12-05 02:12:43 25 4
gpt4 key购买 nike

我正在使用 Gatsby 作为我的 React 应用程序的启动器。为了处理内容,我正在使用 Contentful。

在我的内容模型中,我创建了以下内容类型:

  • 短文本
  • 短文本
  • 媒体
  • 富文本
  • 富文本

使用 Gatsby 的 gatsby-source-contenful 和 @contentful/gatsby-transformer-contentful-richtext 插件,我已经成功呈现了所有这些内容类型,除了我的富文本类型我无法呈现嵌入式其中的 Assets 。

我已尝试通过 npm 安装 @contentful/rich-text-types 并根据 Gatsby 文档中的示例使用常量 MARK 和 INLINES found here

const { MARKS, INLINES } = require('@contentful/rich-text-types')
{
resolve: `@contentful/gatsby-transformer-contentful-richtext`,
options: {
renderOptions: {
/*
* Defines custom html string for each node type like heading, embedded entries etc..
*/
renderNode: {
// Example
[INLINES.ASSET_HYPERLINK]: node => {
return `<img class='custom-asset' src="${
node.data.target.fields.file['en-US'].url
}"/>`
},
[INLINES.EMBEDDED_ENTRY]: node => {
return `<div class='custom-entry' />${
node.data.target.fields.name['en-US']
}</div>`
},
},
/*
* Defines custom html string for each mark type like bold, italic etc..
*/
renderMark: {
// Example
[MARKS.BOLD]: text => `<strong>${text}<strong>`,
},
},
},
},

理想情况下,我希望 Gatbsy 自动将 Rich Text 类型中的图像资源呈现为 <img src="[ASSET URL]" alt="[ASSET DESCRIPTION]">

最佳答案

试试这个:

const { BLOCKS } = require('@contentful/rich-text-types')
...
renderNode: {
[BLOCKS.EMBEDDED_ASSET]: node => {
// console.log(node)
let { description, title, file } = node.data.target.fields
// console.log(file["en-US"].url)
return <img src={file["en-US"].url} />
},
},

这似乎对我有用,尽管图像似乎是全尺寸的,而且加载速度相当慢。需要额外的工作,但这似乎确实有效(至少在开发中)

编辑:
当我发送我的 graphql 查询时,我的 node.data.target 上的 fields 属性似乎停止出现......这停止工作...... super 奇怪

编辑 2:如果删除 .cache 文件夹 (project-root/.cache),上述问题将得到解决。 https://github.com/gatsbyjs/gatsby/issues/10592

关于reactjs - 如何使用 Gatsby 从 Contentful Rich Text 字段中调用和使用嵌入式 Assets ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55554313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com