在危险的SetInnerHTML中传递反应组件

I a*_*m L 5 javascript reactjs

服务器返回类似以下内容:

content = <p> Hello world :smile: <strong> NICE </strong> !</p>- 这是因为我们支持 markdown。

现在我有一个解析器,可以将所有内容解析:{text}:为表情符号。我正在用emoji-mart这个。

这就是现在的内容:

<p> Hello world ${<Emoji emoji=":smile:" />} <strong> NICE </strong> !</p>

目前,如果没有表情符号解析器,我们要做的是:

return React.createElement('div', { 
   dangerouslySetInnerHTML: {
    __html: content,
  }
});
Run Code Online (Sandbox Code Playgroud)

但是,由于我们现在连接 来content包含表情符号 from,emoji-mart我将如何在dangerouslySetInnerHTML不破坏降价的情况下将其传递给?

I a*_*m L 2

在尝试这种情况后,我发现您实际上可以传递使用功能组件并返回字符串: 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>
  );
}
Run Code Online (Sandbox Code Playgroud)

并将其称为:

function testComponent(props) {
  const { content } = props; // content is a markdown and can be a stringified image tag

  return testComponent({ children: content, html: true });
}
Run Code Online (Sandbox Code Playgroud)

对于dangerouslySetInnerHTML

(在你的反应组件中渲染函数)

render() {
    const props = {
      dangerouslySetInnerHTML: {
        __html: testComponent(this.props.content),
      },
    };

    return React.createElement('div', props);
Run Code Online (Sandbox Code Playgroud)

}

这比使用更黑客,但更便宜:

renderToString()
renderToStaticMarkup()
Run Code Online (Sandbox Code Playgroud)