最终的效果类似这样:

根据树状数据渲染树状下拉选项_根据树状数据渲染树状下拉选项

作者是把非末级的选项给禁用了,如果你们需求是要不禁用求留意笔者渲染时的操作。


接下来我们一起来做这个效果:

笔者所用的是react + antd,用其他的架构也是类似,请自行举一反三:

一:首先要处理从后端拿到的数据:

处理成类似这种结构:

根据树状数据渲染树状下拉选项_进入非末级选项_02

上面数据的关键点笔者已经指出来了,我们来渲染树状选择框就是要根据以上关键点递归渲染。

根据数据递归渲染选择框:

import React, { Component } from 'react';
import { TreeSelect } from 'antd'; //从antd引入treeselect组件
/* ··引入你其他的依赖·· */

const { TreeNode } = TreeSelect;

export default class Test extends Component {
constructor(props) {
super(props);
this.state = {
assetLocationList: [],
}
}
async componentDidMount() {
await this.getAssetLocationList();
}

getAssetLocation = async () => {
/* 从后端获取数据并进行处理而后更改state的assetLocationList */
}

//递归渲染节点
genTreeNode = event => {
if (!event.isLeaf && event.children) {
return (
<TreeNode
value={event.value}
title={event.name}
key={event.value}
disabled={!event.isLeaf} //如果你的需求不需要禁用非末级请把此行代码删掉
>
{event.children.map(item => this.genTreeNode(item))}
</TreeNode>
);
} else {
return (
<TreeNode
value={event.value}
title={event.name}
key={event.value}
disabled={!event.isLeaf} //如果你的需求不需要禁用非末级请把此行代码删掉
/>
);
}
}

render() {
const { assetLocationList } = this.state;
return (
<div>
<TreeSelect
style={{ width: 130 }}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
allowClear
onChange={() => /* 当选择更改时你要进行的事件 */}
>
{
assetLocationList.map(item => {
if (!item.isLeaf && event.children) {
return this.genTreeNode(item);
} else {
return (
<TreeNode
value={item.value}
title={item.name}
key={item.value} //找个唯一标识作为节点的key
/>
)
}
})
}
</TreeSelect>
</div>
)
}
}

这样我们的需求就完成了哈~ 恭喜 ~