2017-09-07 42 views
0

我想渲染一个有注释的html组件,以便评论在DOM中显示为注释。在反应组件的html中渲染评论

我现在有

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

但我想有

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

    <!-- Some information here --> 

</head> 

而且我想避免使用下列内容:

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

的可能的复制[如何呈现反应的HTML注释?](https://stackoverflow.com/questions/40015336/how-to-render-a-html-comment-in-react) – Li357

+1

另请参阅https://stackoverflow.com/q/40381851/5647260 – Li357

+0

所有这些解决方案都使用内部,外部或危险 – es3735746

回答

1

一旦组件安装,你可以检索当前DOM元素,然后应用一些DOM操作将HTML注释放在任何地方需要。您可以在下面找到由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); 
}