在 React 组件中解析和呈现外部 HTML

Avi*_*Avi 8 javascript reactjs

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

我需要:

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

例如,如果我收到下面的 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>
Run Code Online (Sandbox Code Playgroud)

问题:

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

我尝试过的事情:

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

Avi*_*Avi 11

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

在此处发布代码,以防评论中的链接断开

该解决方案使用 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"));
Run Code Online (Sandbox Code Playgroud)