antd TreeSelect 禁止选中父级,只能选择子级
# TreeSelect 禁止选中父级需求:只能选中子级,不能不能选择实现效果:未选中效果选中效果废话不多说,直接上代码#### 关键代码:const renderTreeNodes = data =>data.map(item => {if (item.children) {// 这一句是关键代码,设置父级都为禁用模式,有条件的让后台返回item.disabled = true;re
·
TreeSelect 禁止选中父级
需求:只能选中子级,不能不能选择
实现效果:
未选中效果选中效果
废话不多说,直接上代码
关键代码:
const renderTreeNodes = data =>
data.map(item => {
if (item.children) {
// 这一句是关键代码,设置父级都为禁用模式,有条件的让后台返回
item.disabled = true;
return (
<TreeNode
key={item.key}
title={item.label}
value={item.value}
disabled={item.disabled}
>
{renderTreeNodes(item.children)}
</TreeNode>
);
}
return <TreeNode {...item} key={item.key} title={item.label} value={item.value} />;
});
完整代码:
纯组件 TreeNodeSelect
import React from 'react';
import { TreeSelect } from 'antd';
const { TreeNode } = TreeSelect;
export default ({ treeData = [], onChange, value = [], placeholder = '请选择消息提醒人' }) => {
const onNodeChange = values => {
console.log('val', values);
onChange(values);
};
const renderTreeNodes = data =>
data.map(item => {
if (item.children) {
item.disabled = true;
return (
<TreeNode key={item.key} title={item.label} value={item.value} disabled={item.disabled}>
{renderTreeNodes(item.children)}
</TreeNode>
);
}
return <TreeNode {...item} key={item.key} title={item.label} value={item.value} />;
});
return (
<TreeSelect
showSearch
style={{ width: '100%' }}
value={value}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder={placeholder}
treeNodeFilterProp="label"
allowClear
multiple
treeDefaultExpandAll
onChange={values => onNodeChange(values)}
>
{renderTreeNodes(treeData)}
</TreeSelect>
);
};
调用:
const treeData = [
{
key: 10,
value: 10,
label: '项目部',
children: [
{
key: 84,
value: 100084,
label: '伍',
},
{
key: 83,
value: 100083,
label: '黄',
},
{
key: 85,
value: 100085,
label: '樊',
},
],
},
];
<TreeNodeSelect treeData={treeData} onChange={onChange} value={value}>
如果有写错的地方请指正!蟹蟹啦!
更多推荐
所有评论(0)