【发布时间】:2018-05-22 13:56:50
【问题描述】:
我有两个函数,一个是解析 html 字符串以将其标题放入数组中
const str = "<h1>test-1<h1><h2>test1-1<h2><h3>test1-1-1</h3><h1>test1-2<h1><h2>test1-2-1</h2><h3>test1-2-2</h3><h1>test-2</h1><h1>test-3</h1><h1>test-4</h1>
"
const wrapper = document.createElement('div');
wrapper.innerHTML = str.trim();
let tree = [];
let leaf = null;
for (const node of wrapper.querySelectorAll("h1, h2, h3, h4, h5, h6"))
{
const nodeLevel = parseInt(node.tagName[1]);
const newLeaf = { level: nodeLevel, text: node.textContent, children: [], parent: leaf };
while (leaf && newLeaf.level <= leaf.level)
leaf = leaf.parent;
if (!leaf)
tree.push(newLeaf);
else
leaf.children.push(newLeaf);
leaf = newLeaf;
}
另一个将这些标题解析为目录功能的列表
const ol = document.createElement("ol");
(function makeOl(ol, leaves)
{
for (const leaf of leaves)
{
const li = document.createElement("li");
li.appendChild(new Text(leaf.text));
if (leaf.children.length > 0)
{
const subOl = document.createElement("ol");
makeOl(subOl, leaf.children);
li.appendChild(subOl);
}
ol.appendChild(li);
}
})(ol, tree);
它会输出这样的字符串
"<ol><li>test-1<ol><li>test1-1<ol><li>test1-1-1</li></ol></li><li>test1-2<ol><li>test1-2-1</li><li>test1-2-2</li></ol></li></ol></li><li>test-2</li><li>test-3</li><li>test-4</li></ol>"
渲染成类似
的东西- 测试1
- test1-1
- test1-1-1
- 测试1-2
- test1-2-1
- test1-2-2
- test1-1
- 测试2
- test-3
- test-4
我仍然习惯于 React 的 jsx 部分,我想知道如何转换该函数,以便 ol 和 li 是 React/jsx 元素而不是原始 html 字符串,因为这需要另一个步骤渲染例如。
<div dangerouslySetInnerHTML={{__html: olString}} />
我使用 jsx 和数组的方式是这样的
const list = tree.map((headers) => <li>{headers.value}</li>)
<div><ul>{list}</ul></div>
【问题讨论】:
-
我不确定你在这里问什么。 JSX 只是一个语法规范。您是否只是想将已解析的 HTML 树重建为 React 元素节点树?
-
@LINKIWI,没错
标签: javascript reactjs