gpt4 book ai didi

javascript - 将函数转换为 jsx

转载 作者:行者123 更新时间:2023-12-01 02:02:08 25 4
gpt4 key购买 nike

我有两个函数,一个用于解析 html 字符串以将其 header 放入数组中

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. test-1
    1. test1-1
      1. test1-1-1
    2. test1-2
      1. 测试1-2-1
      2. 测试1-2-2
  2. 测试2
  3. 测试-3
  4. 测试-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 元素设置为变量。

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

然后在树组件中

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

关于javascript - 将函数转换为 jsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50469557/

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