Avi*_*Avi 8 javascript reactjs
我正在编写一个基于 React 的应用程序,其中一个组件将其 HTML 内容作为 props 中的字符串字段接收。此内容由 API 调用返回。
我需要:
例如,如果我收到下面的 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)
问题:
我尝试过的事情:
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)
| 归档时间: |
|
| 查看次数: |
6432 次 |
| 最近记录: |