1-数据源
`
const treeData = [ { children: [ { children: [ { title: "leaf", key: "16", children: [ { children: [ { title: "leaf", key: "19", children: [ { title: "leaf", key: "1", children: [],
},
{
title: "leaf",
key: "21",
children: [],
},
],
},
],
title: "parent 1-0",
key: "3",
},
{
children: [
{
title: "leaf",
key: "19",
children: [
{
title: "leaf",
key: "23",
children: [],
},
{
title: "leaf",
key: "24",
children: [],
},
],
},
],
title: "parent 1-0",
key: "3",
},
],
},
],
title: "parent 1-0",
key: "3",
},
{
children: [
{
title: "leaf",
key: "15",
children: [
{
children: [
{
title: "leaf",
key: "19",
children: [
{
title: "leaf",
key: "166",
children: [],
},
{
title: "leaf",
key: "212",
children: [],
},
],
},
],
title: "parent 1-0",
key: "3",
},
{
children: [
{
title: "leaf",
key: "19",
children: [
{
title: "leaf",
key: "555",
children: [],
},
{
title: "leaf",
key: "271",
children: [],
},
],
},
],
title: "parent 1-0",
key: "3",
},
],
},
],
title: "parent 1-0",
key: "6",
},
],
title: "parent 1",
key: "7",
},
{
children: [
{
children: [
{
title: "leaf",
key: "8",
children: [
{
children: [
{
title: "leaf",
key: "19",
children: [
{
title: "leaf",
key: "888",
children: [],
},
{
title: "leaf",
key: "889",
children: [],
},
],
},
],
title: "parent 1-0",
key: "3",
},
{
title: "leaf",
key: "10",
children: [],
},
],
},
],
title: "parent 1-0",
key: "11",
},
{
children: [
{
title: "leaf",
key: "12",
children: [
{
children: [
{
title: "leaf",
key: "19",
children: [
{
title: "leaf",
key: "1524",
children: [],
},
{
title: "leaf",
key: "2122",
children: [],
},
],
},
],
title: "parent 1-0",
key: "3",
},
{
children: [
{
title: "leaf",
key: "19",
children: [
{
title: "leaf",
key: "563",
children: [],
},
{
title: "leaf",
key: "22321",
children: [],
},
],
},
],
title: "parent 1-0",
key: "3",
},
],
},
],
title: "parent 1-0",
key: "15",
},
],
title: "parent 2",
key: "16",
},
];
`
2-递归找到最深层的 children,将想要添加的数组push进去,再次调用函数需要return。不然数据会存在undefined。
`
const addArr = (list, id) => {
if (list.children != []) {
list.children.forEach((item) => {
return addArr(item, id);
});
}
if (list.children.length == 0 && list.key == id) {
list.children.push([1, 2, 3]);
}
};
`
3-首先要将数据进行遍历,再执行递归函数
`
treeData.forEach((item) => {
addArr(item, "1");
});
`
4-在oncheck-Api这里在改变数据源后,组件不会更新,需要对数据源设置为函数,设置数据源时定义状态State,在函数里进行判断,什么时候改变数据源,在useEffect里进行监听