-->

Insert HTML comments in React

2020-08-09 14:35发布

问题:

Is there a way to insert an HTML comment node in React JSX, in the same way you might insert a component or DOM node?

E.g., something like:

React.createElement(Comment, {}, "comment text");

Would render to:

<!-- comment text -->

The idea is that the comment be visible on the page, so { /* this /* } doesn't answer my question.

Note that the following related question doesn't have an answer and asks for something somewhat different:

How to render a HTML comment in React?

I just want to render a single comment node. I notice that React infrastructure renders HTML comments on its own, so perhaps there is a (slightly hacky?) way to do it too.

回答1:

Only thing I could think of would be to manipulate the DOM on componentDidMount and add your comment there, but then React wouldn't be handling that DOM manipulation so it might cause some issues?

    var HTMLComment = React.createClass({

      componentDidMount: function(){
        var htmlComment = "<!--" + this.props.comment + "-->"; 
          this.span.innerHTML = htmlComment;
      },

      render: function(){
        return (
            <span ref={(span) => this.span = span} ></span>
        )
      }
    })


回答2:

Another alternative is to use dangerouslySetInnerHTML

<div dangerouslySetInnerHTML={{ __html: '<!-- comment text -->' }} />

dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it's dangerous.

https://facebook.github.io/react/docs/dom-elements.html#dangerouslysetinnerhtml