内容:documentToHtmlString 不包含富文本中的嵌入图像



我有以下富文本文档

{  
"data":{},
"content":[  
{  
"data":{},
"content":[  
{  
"data":{},
"marks":[ ],
"value":"test",
"nodeType":"text"
}, {  
"data":{},
"marks":[],
"value":"",
"nodeType":"text"
}
],
"nodeType":"paragraph"
},
{  
"data":{  
"target":{  
"sys":{  
"space":{  
"sys":{  
"type":"Link",
"linkType":"Space",
"id":"gedg1u5b0yz9"
}
},
"id":"2CzKe2pWvewCiek6w0yyoQ",
"type":"Asset",
"createdAt":"2019-01-07T22:37:55.473Z",
"updatedAt":"2019-01-07T22:37:55.473Z",
"environment":{  
"sys":{  
"id":"master",
"type":"Link",
"linkType":"Environment"
}
},
"revision":1,
"locale":"en-US"
},
"fields":{  
"title":"Test Image",
"description":"Image for testing",
"file":{  
"url":"//images.ctfassets.net/<hidden>/<hidden>/<hidden>/IMG_2878.JPG",
"details":{  
"size":3874595,
"image":{  
"width":5184,
"height":3456
}
},
"fileName":"IMG_2878.JPG",
"contentType":"image/jpeg"
}
}
}
},
"content":[],
"nodeType":"embedded-asset-block"
},
{  
"data":{},
"content":[  
{  
"data":{},
"marks":[],
"value":"",
"nodeType":"text"
}
],
"nodeType":"paragraph"
}
],
"nodeType":"document"
}

当我使用documentToHtmlString(从这里https://www.npmjs.com/package/@contentful/富文本html渲染器)

documentToHtmlString(document);

它输出以下

<p>test</p><p></p>

有人知道如何让它也输出img标记吗?

来源https://github.com/contentful/rich-text/issues/58#issuecomment-452236848

您需要指定如何渲染你可以在这里找到更多关于它的信息https://github.com/contentful/rich-text/tree/master/packages/rich-text-html-renderer#usage

import { BLOCKS } from '@contentful/rich-text-types';
import { documentToHtmlString } from '@contentful/rich-text-html-renderer';
const options = {
renderNode: {
[BLOCKS.EMBEDDED_ENTRY]: (node) => `<custom-component>${customComponentRenderer(node)}</custom-component>`
}
}
documentToHtmlString(document, options);

我的具体决议是:

const options = {
renderNode: {
[BLOCKS.EMBEDDED_ASSET]: ({ data: { target: { fields }}}) =>
`<img src="${fields.file.url}" height="${fields.file.details.image.height}" width="${fields.file.details.image.width}" alt="${fields.description}"/>`,
},
};

这是原始答案和硬编码的动态值,我希望它能帮助读者对具体问题有一个即时的答案:

let options = {
renderNode: {
'embedded-asset-block': (node) =>
`<img class="img-fluid" src="${node.data.target.fields.file.url}"/>`
}
}
let bodyHTML = body ? documentToHtmlString(body, options) : ''
const options = {
renderNode: {
[BLOCKS.EMBEDDED_ASSET]: ({ data: { target: { fields }}}) =>
<div dangerouslySetInnerHTML={{__html: `<img src="${fields.file['en-GB'].url}" alt="${fields.title['en-GB']}"/>`}} />,
},
};

我发现我需要设置dangerouslySetInnerHTML才能在浏览器中正确渲染。

相关内容

  • 没有找到相关文章

最新更新