繁体   English   中英

危险地设置innerHTML React

[英]Dangerously Set innerHTML React

我有 React 前端和 Strapi 后端。

将数据插入我的strapi后端时,我的前端中生成的 output 包含 html 元素。

如何在没有 HTML 元素的情况下显示 output? 我有以下盖茨比代码块,

import ReactMarkdown from "react-markdown"

<ReactMarkdown children={info_} />

{info_} 中的数据与 HTML 元素一起输出,我如何在我的代码中使用 Dangerously Set innerHTML 或有其他方法来实现这一点?

如果您在dangerouslySetInnerHTML属性中显示 html 节点,您的应用程序将面临 XSS 攻击的风险。 长话短说,html 可能包含会伤害用户的恶意代码。 如果这样做,则需要在显示内容之前对其进行清理。 最好的选择是使用久经考验的库,例如sanitize-html-react

您可以使用DOMParser从您的 HTML 输入创建一个文档,然后像这样提取文本:

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

这是一个使用函数形式的示例:

我尝试将其放入片段演示中,但 Stack Overflow 片段环境不喜欢语法。 ☹️你可以复制粘贴到你的JS控制台试试。

请注意,嵌入式脚本永远不会运行,但其源文本包含在 output 中。 如果您只想要创建文档的一部分文本,您可以在创建的文档上使用类似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);

之后,您将拥有纯文本,因此您将不需要dangerouslySetInnerHTML

暂无
暂无

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

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