我有两个函数,一个解析一个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>"


呈现出类似

test-1test1-1test1-1-1test1-2test1-2-1test1-2-2test-2test-3test-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>

最佳答案

您可以随时使用React.createElement

例如

React.createElement('div', null, `Hello ${this.props.toWhat}`);


但是,最佳实践可能是这样的。



// reusable Tree component
export default class Tree extends Component {

  static propTypes = {
    children: PropTypes.array.isRequired
  }

  render() {

    const { children } = this.props

    return (
      <ol>
        {children.map(leaf =>
          <li key={leaf.id}>
            <span>{leaf.text}</span>
            {leaf.children && <Tree children={leaf.children}/>}
          </li>
        )}
      </ol>
    )
  }
}

// (re)use it
function render() {
  return (
    <Tree children={ tree } />
  );
}





您甚至可以将HTML Elements设置为变量。

<Tree children={ tree } listNode="ul" listElementNode="li" />


然后在树组件中

function render() {
    const {listNode: UL, listElementNode: LI} = this.props;
    return (<UL></UL>);
}

07-28 13:45