简体   繁体   中英

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.

Now I have a parser that parses everything with :{text}: into an emoji. I am using emoji-mart for this one.

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?

在这种情况下,您应该使用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 )

So what I did with my other Components are the same, instead of calling a React component I created a function instead:

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 :

(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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM