我不知道如何使用React传递数据的递归方法。
我的想法是使用tree.js做一个递归方法来检查一个文件夹是否有其他文件夹作为子文件夹,最后检查是否存在一个文件来检查是否被解雇以及是否被扩展。
以下是我获得的JSON文件示例:
{
"name": "Nueva Carpeta2",
"key": "0-625",
"isLeaf": false,
"type": "folder",
"expanded": false,
"children": [{
"name": "Nueva Carpeta2",
"key": "0-629",
"isLeaf": false,
"type": "folder",
"expanded": false,
"children": [{
"name": "Nueva Carpeta3",
"key": "0-623",
"isLeaf": false,
"type": "folder",
"expanded": false,
"children": [{
"name": "distribucion33",
"key": "0-99",
"isLeaf": true,
"type": "layer",
"checked": true
}]
}]
}]
}
这是我的代码,我不知道如何制作递归的下一个方法:checkItemCheckeds
和checkExpandedFolders
loadJSON = (tree) => {
this.treeData = [];
this.checkedKeys = [];
this.expandedKeys = [];
this.setState({ treeData: this.treeData, checkedKeys: this.checkedKeys, expandedKeys: this.expandedKeys });
var totalItems = tree.length-1;
tree.forEach( (item, index) => {
this.addItem(item);
if (index === totalItems) {
this.setState({ treeData: this.treeData, checkedKeys: this.checkedKeys, expandedKeys: this.expandedKeys });
}
});
}
addItem = (data) => {
var dataItem = {
name: data.name,
key: data.key,
isLeaf: data.isLeaf,
type: data.type
};
if (data.checked !== undefined) {
dataItem.checked = data.checked;
}
if (data.expanded !== undefined) {
dataItem.expanded = data.expanded;
}
if (data.children !== undefined && data.children.length > 0) {
dataItem.children = data.children;
}
this.checkItemCheckeds(data);
this.checkExpandedFolders(data);
this.treeData.unshift(dataItem);
}
checkItemCheckeds = (data) => {
if (data.children !== undefined && data.children.length > 0) {
data.children.forEach( (item) => {
if (item.checked) {
this.checkedKeys.unshift(item.key);
}
});
} else {
if (data.checked) {
this.checkedKeys.unshift(data.key);
}
}
}
checkExpandedFolders = (data) => {
if (data.expanded) {
this.expandedKeys.unshift(data.key);
}
}
编辑:
我做了这个方法,但是没有儿童用品。
checkItemCheckeds = (data) => {
if (data.children !== undefined) return this.checkItemCheckeds(data.children);
else {
if (data.checked) {
return this.checkedKeys.unshift(data.key);
} else {
return;
}
}
}
这是完整的json文件:https://pastebin.com/Fa8j6Eqk
求助:
checkItemCheckeds = (data) => {
if (data.children !== undefined) {
data.children.forEach( (item) => {
(item.checked) ? this.checkedKeys.unshift(item.key) : this.checkItemCheckeds(item);
});
}
}
答案 0 :(得分:1)
简单回忆一下这个组件:
import React from "react";
const Leaf = ({ data = [] }) =>
data.map(({ key, isLeaf, name, children }) => !isLeaf
? <ul key={key}>{name}{getChilds(children)}</ul>
: <li key={key}>{name}</li>
);
function getChilds(data) {
return data && <Leaf data={data} />
}
export default Leaf
这是一个完整的demo。
答案 1 :(得分:0)
例如
const testMethod = obj => {
if (obj.children) return testMethod(obj.children)
return obj
}