简体   繁体   English

反应渲染粘贴 html 作为标签,而不是字符串

[英]React render pasted html as tags, not string

I have a quick question.我有一个快速的问题。 I am currently developing a React app with Python on the backend.我目前正在开发一个在后端使用 Python 的 React 应用程序。 On the Python side, I parse some html files, and I extract some html tags from them.在 Python 方面,我解析了一些 html 文件,并从中提取了一些 html 标签。 Then it gets packed into a JSON and sent to the frontend.然后它被打包到 JSON 并发送到前端。 So React app receives something like this:所以 React 应用程序会收到这样的信息:

{'<b>id</b>': '<a href="https://example.com?foo=42">Link</a>'}

So those are like raw html tags in form of strings.所以这些就像字符串形式的原始 html 标签。 Now I want to render them.现在我想渲染它们。 And this happens:这会发生:

在此处输入图像描述

And this is how it looks under dev tools:这就是它在开发工具下的样子:

在此处输入图像描述

So it gets rendered as literal string and what I want is the text on the left side to be bold, and the text on the other side to be an actual hyperlink.所以它被渲染为文字字符串,我想要的是左侧的文本是粗体,而另一侧的文本是一个实际的超链接。 Is there a way to do it?有没有办法做到这一点?

React stops this intentionally. React 故意阻止了这一点。 See the docs .请参阅文档

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) 攻击。

You can still accomplish it by using dangerouslySetInnerHTML .您仍然可以通过使用dangerouslySetInnerHTML来完成它。 Replace the following test div with your variable holding html.将以下测试 div 替换为包含 html 的变量。

const test = "<div>TEST</div>";
return <div dangerouslySetInnerHTML={{__html: test }} />;

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

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