我试图在我的博客中集成内容丰富的文本,它只使用粗体、段落和斜体。我不能让图像和嵌入的东西出现。
首先,我有这个组件:
const Content = ({ content }) => {
return (
<div className="content-body-contentful">
{documentToReactComponents(content)}
</div>
)
}然后,在post页面中,我导入该组件并传递de data,如下所示:
<Content content={article.fields.body} />
这个问题有什么答案吗?
发布于 2021-10-22 05:31:34
Hi @user13680445 contentful中的Richtext字段总是返回如下内容,至少作为Graphql响应
"richTextResponse": {
// JSON structure of the Rich Text field
"json": {
# ...
}
// all referenced assets/entries
"links": {
# ...
}
}在links字段中,您将获得嵌入到Richtext中的所有资产和条目
下面我用Typescript编写了一个如何添加资产的示例
export const renderOptions = (links: Links): Options => {
const assetMap = getAssets(links.assets.block);
const entryMap = getEntries(links.entries.block);
return {
renderNode: {
[BLOCKS.HEADING_1]: renderHeading,
[BLOCKS.PARAGRAPH]: renderParagraph,
[BLOCKS.EMBEDDED_ENTRY]: renderEntry(entryMap),
[BLOCKS.EMBEDDED_ASSET]: renderAsset(assetMap),
},
};
};
const renderAsset =
(assetMap: Map<string, ContentfulImage>): NodeRenderer =>
(node) => {
const asset = assetMap.get(node.data.target.sys.id);
if (!asset) {
return <></>;
}
switch (asset.contentType) {
case "video/mp4":
return (
<VideoAsset
url={asset.url}
width={asset.width}
height={asset.height}
/>
);
case "image/png":
case "image/jpeg":
return (
<ImageAsset
url={asset.url}
width={600}
height={450}
description={asset.description}
quality={75}
/>
);
default:
return "Nothing to see here...";
}
};然后你可以像这样调用这个函数:
{documentToReactComponents(json, renderOptions(links))}
这是一种最基本的方法,但眼下知足并没有更好的方法。
在这里,我们获得了与nodeType中的sys.id和资产链接中的sys.id相匹配的资产数据,例如:
RichText Object
{
"nodeType": "embedded-asset-block",
"content": [],
"data": {
"target": {
"sys": {
"id": "2DdSHQJA8zoumehPzqWZrs",
"type": "Link",
"linkType": "Asset"
}
}
}
}链接对象
"links": {
"assets": {
"block": [
{
"sys": {
"id": "2DdSHQJA8zoumehPzqWZrs"
},
"fileName": "GOPR0511.JPG",
"url": "https://images.ctfassets.net/",
"title": "GOPR0511"
}
]
}
}我们基于2DdSHQJA8zoumehPzqWZrs (本例中是sys.id )将两者连接起来
发布于 2021-01-28 14:50:42
下面是通过Contentful将图像与Next.js结合使用的示例。您可以以类似的方式实现其余的项。
import Image from 'next/image'
const renderProps = {
renderNode: {
[BLOCKS.EMBEDDED_ASSET]: node => {
let { description, file } = node.data.target.fields
return (
<picture>
<Image src={file.url} alt={description} />
</picture>
)
},
},
}
const Content = ({ content }) => {
return <div className="content-body-contentful">{documentToReactComponents(content, renderProps)}</div>
}https://stackoverflow.com/questions/62197258
复制相似问题