【问题标题】:How to get Reference Fields in embedded block's using Gatsby and Contentful's Rich Text fields如何使用 Gatsby 和 Contentful 的富文本字段在嵌入块中获取参考字段
【发布时间】:2025-12-01 16:25:01
【问题描述】:

我有一个富文本编辑器字段,它接受一个嵌入块,其中内容类型包含指向另一个内容类型的引用链接。

像这样:

content (rich text field)
  - group (embedded block)
    - group-items (reference field)
      - item 1 (referenced content)
      - item 2 (referenced content)

如何使用@contentful/rich-text-react-renderer 获取referenced content 项目?

我目前有这个:

import { MARKS, BLOCKS } from '@contentful/rich-text-types';
import { documentToReactComponents } from '@contentful/rich-text-react-renderer';

const options = {
  renderNode: {
    [BLOCKS.EMBEDDED_ENTRY]: (node) => {
      console.log(node);
      return true;
    }
  },
  renderText: text => text.replace('!', '?'),
};

这给了我一堆 id,但不是我真正想要的条目的字段数据。

content: []
data:
target: {sys: {…}}
__proto__: Object
nodeType: "embedded-entry-block"

content: []
data:
target:
sys: {id: "c13cBu2W6nOkQMx6bsvqCE5", type: "Link", linkType: "Entry"}
__proto__: Object
__proto__: Object
nodeType: "embedded-entry-block"
__proto__: Object

【问题讨论】:

    标签: reactjs gatsby contentful


    【解决方案1】:

    我在这里遇到了 2 个问题。

    首先,有时 Gatsby 的缓存会导致从内容中检索新数据的问题,因此您可能只会得到 sys 而不是 fields。这就是发生在我身上的事情。

    只需删除.cache 并重新运行yarn run dev 就可以了。

    其次,要使用输入块获取多个内容类型,这可以通过查找输入块sys.id 来实现。这样您就可以创建不同的组件来处理各种内容类型。

    [BLOCKS.EMBEDDED_ENTRY]: (node) => {
          const fields = node.data.target.fields;
    
          switch (node.data.target.sys.contentType.sys.id) {
            case 'group-item':
              return <div>
                <GroupItem name={fields.name['en-US']} />
              </div>
            default:
               return <div>Fallback Element</div>
    }
    

    【讨论】:

      最近更新 更多