Insert HTML comments in React

﹥>﹥吖頭↗ 提交于 2019-12-22 03:41:37

问题


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:


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




回答2:


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


来源:https://stackoverflow.com/questions/40381851/insert-html-comments-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!