[英]How to Render a react component inside a dangerouslySetInnerHTML content?
[英]Pass react component inside dangerouslySetInnerHTML
服務器返回如下內容:
content = <p> Hello world :smile: <strong> NICE </strong> !</p>
-這是因為我們支持降價促銷。
現在,我有了一個解析器,可以使用:{text}:
將所有內容解析為一個表情符號。 我正在為此使用emoji-mart
。
因此,現在的內容如下所示:
<p> Hello world ${<Emoji emoji=":smile:" />} <strong> NICE </strong> !</p>
當前沒有表情符號解析器,我們要做的是:
return React.createElement('div', {
dangerouslySetInnerHTML: {
__html: content,
}
});
但是,由於我們現在將content
串聯起來以包含來自emoji-mart
的Emoji,我如何在不破壞markdown的情況下將其傳遞給dangerouslySetInnerHTML
SetInnerHTML?
在這種情況下,您應該使用React.renderToStaticMarkup(JSXInstance)
:
<p> Hello world ${React.renderToStaticMarkup(<Emoji emoji=":smile:" />)} <strong> NICE </strong> !</p>
在解決這種情況后,我發現您實際上可以傳遞使用功能的組件並改為返回字符串: https : //github.com/missive/emoji-mart#using-with-dangerouslysetinnerhtml (特定於我有關emoji-mart
問題)
因此,我對其他組件所做的操作是相同的,而不是調用React組件,而是創建了一個函數:
function testComponent(props) {
const { style, className, children, html } = props;
if (html) {
return `<span style='${style}' class='${className}'>${children || ''}</span>`;
}
return (
<span style="${style}" class="${className}">
${children || ''}
</span>
);
}
並將其稱為:
function testComponent(props) {
const { content } = props; // content is a markdown and can be a stringified image tag
return testComponent({ children: content, html: true });
}
對於dangerouslySetInnerHTML
:
(反應組件內部的渲染功能)
render() {
const props = {
dangerouslySetInnerHTML: {
__html: testComponent(this.props.content),
},
};
return React.createElement('div', props);
}
這更駭人,但比使用以下工具便宜:
renderToString()
renderToStaticMarkup()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.