简体   繁体   English

在React中插入HTML注释

[英]Insert HTML comments in React

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? 有没有办法在React JSX中插入HTML注释节点,就像插入组件或DOM节点一样?

Eg, 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. 这个想法是评论在页面上可见,所以{ /* this /* }不回答我的问题。

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? 如何在React中呈现HTML注释?

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. 我注意到React基础架构自己呈现HTML注释,所以也许有一种(稍微有些hacky?)方式也可以。

Another alternative is to use dangerouslySetInnerHTML 另一种方法是使用dangerouslySetInnerHTML

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

dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM. dangerouslySetInnerHTML是React在浏览器DOM中使用innerHTML的替代品。 In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack. 通常,从代码设置HTML是有风险的,因为很容易无意中将您的用户暴露给跨站点脚本(XSS)攻击。 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. 因此,您可以直接从React设置HTML,但是您必须键入dangerouslySetInnerHTML并使用__html键传递对象,以提醒自己这很危险。

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

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? 我唯一能想到的就是操作componentDidMount上的DOM并在那里添加你的注释,但是React不会处理那个DOM操作,所以它可能会导致一些问题?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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