简体   繁体   English

在react组件的html中渲染注释

[英]Render a comment in the html of a react component

I am trying to render an html component that has a comment it so that the comment shows up in the DOM as comment. 我试图呈现一个带有注释的html组件,以便该注释作为注释显示在DOM中。

I currently have 我目前有

<head>
    <title>{props.pageTitle}</title>
</head>

But I would like to have 但我想有

<head>
    <title>{props.pageTitle}</title>

    <!-- Some information here --> 

</head>

And I would like to avoid using the following: 而且我想避免使用以下内容:

dangerouslySetHtml
element.innerHTML = "...";
element.outerHTML = "...";

Once the component mounted, you could retrieve the current DOM element and, then apply some DOM operations to place the HTML comment wherever you need. 一旦安装了组件,就可以检索当前的DOM元素,然后应用一些DOM操作将HTML注释放置在需要的地方。 You can find below an example of a component wrapped by HTML comments. 您可以在下面找到由HTML注释包裹的组件示例。

componentDidMount() {       
    // Get current node
    let currentNode = ReactDOM.findDOMNode(this);
    // Get parent node
    let parentNode = currentNode.parentNode;
    // Create the comment to insert before
    let commentBefore = document.createComment("Begin Tag");
    parentNode.insertBefore(commentBefore, currentNode);
    // Create the comment to insert after
    let commentAfter = document.createComment("End Tag");
    parentNode.insertBefore(commentAfter, currentNode.nextSibling);
}

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

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