[英]Pass react component inside dangerouslySetInnerHTML
The server returns something like: 服务器返回如下内容:
content = <p> Hello world :smile: <strong> NICE </strong> !</p>
- this is because we support markdown. content =
<p> Hello world :smile: <strong> NICE </strong> !</p>
-这是因为我们支持降价促销。
Now I have a parser that parses everything with :{text}:
into an emoji. 现在,我有了一个解析器,可以使用
:{text}:
将所有内容解析为一个表情符号。 I am using emoji-mart
for this one. 我正在为此使用
emoji-mart
。
So this is what content looks like now: 因此,现在的内容如下所示:
<p> Hello world ${<Emoji emoji=":smile:" />} <strong> NICE </strong> !</p>
Currently without the emoji parser what we do is: 当前没有表情符号解析器,我们要做的是:
return React.createElement('div', {
dangerouslySetInnerHTML: {
__html: content,
}
});
However, since we now concatenating the content
to contain the Emoji from emoji-mart
how will I pass this to dangerouslySetInnerHTML
without breaking the markdown? 但是,由于我们现在将
content
串联起来以包含来自emoji-mart
的Emoji,我如何在不破坏markdown的情况下将其传递给dangerouslySetInnerHTML
SetInnerHTML?
在这种情况下,您应该使用React.renderToStaticMarkup(JSXInstance)
:
<p> Hello world ${React.renderToStaticMarkup(<Emoji emoji=":smile:" />)} <strong> NICE </strong> !</p>
Upon playing around with the situation I discovered that you can actually pass use functional components and return string instead: https://github.com/missive/emoji-mart#using-with-dangerouslysetinnerhtml (Specific for my problem regarding emoji-mart
) 在解决这种情况后,我发现您实际上可以传递使用功能的组件并改为返回字符串: https : //github.com/missive/emoji-mart#using-with-dangerouslysetinnerhtml (特定于我有关
emoji-mart
问题)
So what I did with my other Components are the same, instead of calling a React component I created a function instead: 因此,我对其他组件所做的操作是相同的,而不是调用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>
);
}
And called it as: 并将其称为:
function testComponent(props) {
const { content } = props; // content is a markdown and can be a stringified image tag
return testComponent({ children: content, html: true });
}
And for the dangerouslySetInnerHTML
: 对于
dangerouslySetInnerHTML
:
(render function inside of your react component) (反应组件内部的渲染功能)
render() {
const props = {
dangerouslySetInnerHTML: {
__html: testComponent(this.props.content),
},
};
return React.createElement('div', props);
} }
This is hackier, but less expensive than using: 这更骇人,但比使用以下工具便宜:
renderToString()
renderToStaticMarkup()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.