我有以下富文本文档
{
"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/rich-text-html-renderer开始)
documentToHtmlString(document);
它输出以下内容
<p>test</p><p></p>
任何人都知道如何获取它来输出img标签吗?
答案 0 :(得分:2)
来自https://github.com/contentful/rich-text/issues/58#issuecomment-452236848
您需要指定渲染方式 您可以在https://github.com/contentful/rich-text/tree/master/packages/rich-text-html-renderer#usage
中找到更多相关信息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}"/>`,
},
};
答案 1 :(得分:1)
这是原始答案和硬编码的动态值, 我希望它可以帮助读者立即对具体问题做出回答:
let options = {
renderNode: {
'embedded-asset-block': (node) =>
`<img class="img-fluid" src="${node.data.target.fields.file.url}"/>`
}
}
let bodyHTML = body ? documentToHtmlString(body, options) : ''
答案 2 :(得分:0)
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
才能使其在浏览器中正确呈现。