我正在使用 Contentful 的 Content Delivery API 检索内容。我的数据包含一个具有富文本数据类型的字段。我正在使用 Contentful 的 rich-text-react-renderer 为我的富文本字段中的元素创建所需的 React 组件。但是当我为 BLOCK.PARAGRAPH 添加自定义样式时,我发现它覆盖了我为 BLOCK.QUOTE、BLOCK.UL_LIST、BLOCK.CODE 等添加的样式,这不是我想要的。仅当不存在其他更具体的块样式时,我才希望段落样式成为默认样式。
这似乎是因为返回的 blockquote 数据带有嵌套在 blockquote 节点内的段落节点类型。
这是我的富文本渲染功能:
const richTextRenderParams: RichTextRenderOptions = {
renderNode: {
[INLINES.ENTRY_HYPERLINK]: (node: any, children: any) => styleArticleLink(node, children),
[INLINES.HYPERLINK]: (node, children) => <span>{children}</span>,
[BLOCKS.HEADING_2]: (node, children) => <Typography variant='h2'>{children}</Typography>,
[BLOCKS.HEADING_3]: (node, children) => <Typography variant='h3'>{children}</Typography>,
[BLOCKS.QUOTE]: (node, children) => <Typography sx={calloutStyle}>{children}</Typography>,
[BLOCKS.PARAGRAPH]: (node, children) => <Typography sx={bodyTextStyle}>{children}</Typography>,
},
};
return documentToReactComponents(body, richTextRenderParams);
这是从 Contentful 的 Content Delivery API 返回的数据的形式:
我会要求段落函数仅有条件地应用,但由于它位于另一个节点内部,因此我没有找到访问父对象以确定是否应用段落样式的方法。
此人似乎有类似的问题:https://github.com/contentful/rich-text/issues/88
阅读那里的评论,我了解到我可以在处理引号、列表和其他块样式时删除嵌套的段落元素。
我将块引用的处理方式(如上所示)更改为:
[BLOCKS.QUOTE]: (node, children) => <Typography sx={calloutStyle}>{removeParagraphWrapper(children)}</Typography>
removeParagraphWrapper 函数如下所示:
const removeParagraphWrapper = (nodes: any) => {
if (nodes.length && nodes[0].props.children) {
return nodes[0].props.children
}
return nodes;
}
我对列表和其他样式块进行了类似的处理,这对我有用。现在,段落样式不适用于块引用、代码块或任何其他内容丰富的测试渲染器的块样式。