在线示例https://codesandbox.io/embed/myp00yr1xx?fontsize=14/react-tree2
实现的效果
- 点击分支节点时,展开其子节点
- 点击任意节点都能十分容易的确定对应的节点数据
- 能接受形如下列数组格式的原始节点数据:
[
{
id: 5,
name: "节点0-3-5",
pid: 3
},
{
id: 4,
name: "节点0-3-4",
pid: 3
},
{
id: 0,
name: "根节点",
pid: -1
},
{
id: 6,
name: "节点0-1-6",
pid: 1
},
{
id: 2,
name: "节点0-2",
pid: 0
},
{
id: 3,
name: "节点0-3",
pid: 0
},
{
id: 1,
name: "节点0-1",
pid: 0
}
]
- 能接受形如下列形式的Object的原始节点数据:
{
id: 0,
name: "根节点",
pid: -1,
children: [
{
id: 1,
name: "节点0-1",
pid: 0,
children: [
{
id: 6,
name: "节点0-1-6",
pid: 1
}
]
},
{
id: 2,
name: "节点0-2",
pid: 0
},
{
id: 3,
name: "节点0-3",
pid: 0,
children: [
{
id: 4,
name: "节点0-3-4",
pid: 3
},
{
id: 5,
name: "节点0-3-5",
pid: 3
}
]
}
]
}
关系矩阵
在数据结构中,我们分析图结构的节点之间的关系时,经常提到关系矩阵。我们可以用二维数组定义一个这样的关系矩阵。
// 假设原始节点数据是数组
const createShipMatrix = (origin) => {
if (!origin || !origin.length) return;
const shipMatrix = [];
// 初始化
const len = origin.length;
for (let i = 0; i<len; i++ ){
shipMatrix[i]=[];
}
// 假设有两个节点origin[a]与origin[b],我们令
// shipMatrix[a][b] = 1,表示orgin[a]是origin[b]的父节点;
// shipMatrix[a][b] = -1,表示orgin[a]是origin[b]的子节点;
// shipMatrix[a][b] = 0,表示orgin[a]和origin[b]没有直接关系。
for (let i = 0; i<len; i++) {
for (let j = 0; j<len; j++) {
if (i==j){