如何使用 Gatsby 和 Contentful 的富文本字段获取嵌入块中的参考字段

Dai*_*imz 0 reactjs contentful gatsby

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

像这样:

content (rich text field)
  - group (embedded block)
    - group-items (reference field)
      - item 1 (referenced content)
      - item 2 (referenced content)
Run Code Online (Sandbox Code Playgroud)

我怎样才能referenced content使用物品@contentful/rich-text-react-renderer

我目前有这个:

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('!', '?'),
};
Run Code Online (Sandbox Code Playgroud)

这给了我一堆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
Run Code Online (Sandbox Code Playgroud)

Dai*_*imz 6

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

首先,有时 Gatsby 的缓存会导致从 contentful 检索新数据的问题,因此您可能只会得到sysnot 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>
}
Run Code Online (Sandbox Code Playgroud)