在React中插入HTML注释 [英] Insert HTML comments in React

查看:141
本文介绍了在React中插入HTML注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在React JSX中插入HTML注释节点,就像插入组件或DOM节点一样?

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.createElement(Comment, {}, "comment text");

将呈现给:

<!-- 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:

如何在React中呈现HTML注释?

我只想渲染一个注释节点。我注意到React基础设施自己呈现了HTML注释,所以也许有一种(稍微有些hacky?)方式也可以这样做。

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.

推荐答案

另一种选择是使用 dangerouslySetInnerHTML

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




dangerouslySetInnerHTML是React在浏览器DOM中使用innerHTML的替代品。通常,从代码设置HTML是有风险的,因为很容易无意中将您的用户暴露给跨站点脚本(XSS)攻击。因此,您可以直接从React设置HTML,但是您必须键入dangerouslySetInnerHTML并使用__html键传递对象,以提醒自己这很危险。

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

这篇关于在React中插入HTML注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆