gpt4 book ai didi

reactjs - 使用 Reactjs 来自相同 JSON 的具有父 ID 的嵌套树

转载 作者:行者123 更新时间:2023-12-05 07:27:54 25 4
gpt4 key购买 nike

我正在尝试使用 Reactjs 创建一个嵌套的树。

  • 家长
    • child

我的 JSON 看起来像这样

[{
id: 45,
parentId: 0;
},
{
id: 49,
parentId: 45;
}]

我的想法是创建一个 TreeLevel 并在每个 <li> 上有一个点击处理程序.如果有 child ,它会附加 <ul><li>

//Here is my component call
<TreeLevel pId={pId} treeData={treeData} />

//-- component
const TreeLevel = (props) => {
const temp = props.treeData.filter(tree => {
return tree.parentId === props.pId;
});

const lis = temp.map((li, index) => {
return (
<li key={index} onClick={() => showChildren(li.id, props.treeData)}>
{li.name}

</li>
);
});

return <ul>{lis}</ul>
}

function showChildren(pId, treeData) {
// this doesn't work, but the idea of what I want it to do
return ( <TreeLevel pId={pId} treeData={treeData} />);
}

class Tree extends Component {
render() {
const { treeData, pId } = this.props;

return (
<TreeLevel pId={pId} treeData={treeData} />
);
}
}

这是我来自 App.js 的主要调用

class App extends Component {
state = {
parentId: 0,
treeData: [ // array of objects here
]
};

render() {
const { treeData, pId } = this.state;

return (
<div>
<Tree treeData={treeData} pId={parentId} />
</div>
);
}
}

ReactDOM.render(<App />, document.getElementById('root'));

我可以获得第一级 (parentId = 0),但是当我尝试在每个 <li> 上放置一个点击事件时标签,我不知道如何从 TreeLevel附加 HTML DOM 的组件,更不用说在正确的位置了。

我使用以下教程作为松散指南。 React Tutorial

有什么想法吗?

最佳答案

免责声明:我也是刚刚开始使用 ReactJS。但我希望能帮到你。因此,假设我的建议和代码不是 100% 正确。

一个组件应该总是一个

render() 函数中,您可以写下代码(和 JSX)。但只渲染一个主要元素。如果您有多个项目,请将它们的 JSX 推送到一个数组中。并在稍后呈现该 {array}

import React { Component } from 'react';
import ReactDOM from 'react-dom';

class TreeLevel extends Component {
constructor(props) {
super(props);
}

render() {
const temp = this.props.treeData.filter(tree => {
return tree.parentId === props.pId;
});

let liArray = [];

const lis = temp.map((li, index) => {
liArray.push(
<li key={index} onClick={() => showChildren(li.id, props.treeData)}>
{li.name}
</li>
);
});

return (
<ul>
{liArray}
</ul>
);
}
}

ReactDOM.render(<TreeLevel pId={pId} treeData={treeData} />, document.getElementById("app"));

您的showChildren 函数也应该放在类TreeLevel 中。并且可以用this.showChildren()来引用。

但是,我认为您的基本原理是错误的。我的建议是首先通读文档。我还没有 100% 明白,但我认为它正在慢慢开始点击。

关于reactjs - 使用 Reactjs 来自相同 JSON 的具有父 ID 的嵌套树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53706515/

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