简体   繁体   English

危险地设置innerHTML React

[英]Dangerously Set innerHTML React

I have React frontend and strapi backend.我有 React 前端和 Strapi 后端。

When inserting data into my strapi backend, the resulting output in my frontend contains html elements.将数据插入我的strapi后端时,我的前端中生成的 output 包含 html 元素。

How can I show the output without the HTML elements?如何在没有 HTML 元素的情况下显示 output? I have the following Gatsby code block,我有以下盖茨比代码块,

import ReactMarkdown from "react-markdown"

<ReactMarkdown children={info_} />

The data within {info_} is outputted with the HTML elements, how can I use Dangerously Set innerHTML in my code or is there some other way to achieve this? {info_} 中的数据与 HTML 元素一起输出,我如何在我的代码中使用 Dangerously Set innerHTML 或有其他方法来实现这一点?

If you display an html node within the dangerouslySetInnerHTML property, you put your application at risk for XSS attacks.如果您在dangerouslySetInnerHTML属性中显示 html 节点,您的应用程序将面临 XSS 攻击的风险。 Long story short, the html could contain malicious code that would harm the user.长话短说,html 可能包含会伤害用户的恶意代码。 If you do it, you need to sanitize the content before displaying it.如果这样做,则需要在显示内容之前对其进行清理。 The best option would be to use a battle-tested library such as sanitize-html-react .最好的选择是使用久经考验的库,例如sanitize-html-react

You can use DOMParser to create a document from your HTML input and then extract the text like this:您可以使用DOMParser从您的 HTML 输入创建一个文档,然后像这样提取文本:

new DOMParser().parseFromString(info_, 'text/html').body.textContent;

Here's an example using a functional form:这是一个使用函数形式的示例:

I tried putting this into a snippet demo, but the Stack Overflow snippet environment doesn't like something about the syntax.我尝试将其放入片段演示中,但 Stack Overflow 片段环境不喜欢语法。 ☹️ You can copy and paste it in your JS console to try it. ☹️你可以复制粘贴到你的JS控制台试试。

Note that the embedded script never runs, but its source text is included in the output.请注意,嵌入式脚本永远不会运行,但其源文本包含在 output 中。 If you want just part of the created document's text, you can use a method like Document.querySelector on the created document rather than its body .如果您只想要创建文档的一部分文本,您可以在创建的文档上使用类似Document.querySelector的方法,而不是它的body

function getTextFromHtml (html) {
  const doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent ?? '';
}

// Use:

// assuming `info_` is a string of valid HTML like this:
const info_ = `
<div>
  <p>Some text</p>
  <p>Some more text</p>
  <script>console.log('This script executed!')</script>
</div>
`;

const textContent = getTextFromHtml(info_);
console.log(textContent);

Afterward, you'll have plain text, so you won't need dangerouslySetInnerHTML .之后,您将拥有纯文本,因此您将不需要dangerouslySetInnerHTML

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

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