简体   繁体   English

在React中正确渲染HTML标签

[英]Render HTML tags properly in React

I have to create a text module in React, i'm using JSX too; 我必须在React中创建一个文本模块,我也正在使用JSX。 I will receive the data from a JSON file. 我将从JSON文件接收数据。 For example: 例如:

{ "text-data": "text": "<small> Hello world </small>" }

I tried to do something like this in my module: <p> {this.props.textData.text}</p> 我试图在我的模块中执行以下操作: <p> {this.props.textData.text}</p>

When I try to render this in my JSX file, it show as plain text with the tags included. 当我尝试在JSX文件中呈现此内容时,它显示为包含标签的纯文本。 I've been researching and I found that I could use this function "Dangerously Set innerHTML" but it's not recommended because it can cause an XSS attack. 我一直在研究,发现可以使用此功能“危险地设置innerHTML”,但不建议使用此功能,因为它可能导致XSS攻击。 I read here other answers about this, that say that using HTML entities work; 我在这里阅读了有关此问题的其他答案,即使用HTML实体有效; but I can't make that work for now. 但我暂时无法进行这项工作。

The dangerouslySetInnerHTML prop is there for cases like this. 危险的 SetInnerHTML道具可以在这种情况下使用。 In effect, you're saying that you completely trust the html that you're outputting and that it's valid html. 实际上,您是说您完全信任要输出的html,并且它是有效的html。 You would not want to use it for user input (unless absolutely necessary and thoroughly validated). 您不希望将其用于用户输入(除非绝对必要且经过充分验证)。

See the React documentation for more information. 有关更多信息,请参见React文档 There is also a previous similar StackOverflow question . 前面也有类似的StackOverflow问题

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

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