gpt4 book ai didi

javascript - 在 React 组件中解析和渲染外部 HTML

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:39:37 24 4
gpt4 key购买 nike

我正在编写一个基于 React 的应用程序,其中一个组件接收其 HTML 内容作为 props 中的字符串字段。此内容由 API 调用返回。

我需要:

  1. 将此内容呈现为标准 HTML(即应用样式)
  2. 解析内容以查看内容中的部分是否有“接受评论”标签并在该部分旁边显示“评论”按钮

例如,如果我收到下面的 HTML,我应该在 ID 为“s101”的部分旁边显示“评论”按钮。

<html>
<head/>
<body>
<div id="content">
<section id="s101" accept-comments="true">Some text that needs comments</section>
<section id="s102">Some text that doesn't need comments</section>
</div>
</body>
</html>

问题:

  1. 由于内容可能会变得有点大,有时接近 1MB,解析和呈现 HTML 的最有效方法是什么?
  2. 我如何确保 React 不会重新呈现此组件,因为它不会更新?我假设总是从 shouldComponentUpdate() 返回“false”。

我尝试过的事情:

  1. 使用“dangerouslySetInnerHTML”或“react-html-parser”呈现 HTML。使用此选项,无法解析“接受评论”部分。
  2. 使用 DOMParser().parseFromString 解析内容。如何在 React 组件中将其输出呈现为 HTML?这对于 1MB 以上的内容是否有效?

最佳答案

这个答案来自 Chris G 在评论中的代码。我将代码用于不同大小的文档,效果很好。谢谢克里斯 G!

在这里发布代码以防链接 link在评论中休息。

该解决方案使用 DOMParser 解析 API 调用提供的 HTML 内容,并对其进行扫描以找到应包含“评论”按钮的内容。以下是相关部分。

import React from "react";
import { render } from "react-dom";

const HTML =
"<div><section but='yes'>Section 1</section><section>Section 2</section></div>";

class DOMTest extends React.Component {
constructor(props) {
super(props);

const doc = new DOMParser().parseFromString(HTML, "application/xml");
const htmlSections = doc.childNodes[0].childNodes;

this.sections = Object.keys(htmlSections).map((key, i) => {
let el = htmlSections[key];
let contents = [<p>{el.innerHTML}</p>];

if (el.hasAttribute("but")) contents.push(<button>Comment</button>);

return <div key={i}>{contents}</div>;
});
}

render() {
return <div>{this.sections}</div>;
}
}

const App = () => (
<div>
<DOMTest />
</div>
);

render(<App />, document.getElementById("root"));

关于javascript - 在 React 组件中解析和渲染外部 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49665091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com