在表单中,我们可能会碰到这样的需求,比如我想将某一个物品或者资产,分配到某一个部门的员工下,那么我们需要在表单中做这样的配置:
![](https://img-blog.csdnimg.cn/20191224142915677.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NoZW5xa18xMjM=,size_16,color_FFFFFF,t_70)
这样就会用到antd的treeselect组件,组件很好用,自带搜索框,可以大大的提高用户的可操作性。
我们来看一下代码的结构:
import { TreeSelect } from 'antd';
const { TreeNode } = TreeSelect;
class Demo extends React.Component {
state = {
value: undefined,
};
onChange = value => {
console.log(value);
this.setState({ value });
};
render() {
return (
<TreeSelect
showSearch
style={{ width: '100%' }}
value={this.state.value}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder="Please select"
allowClear
treeDefaultExpandAll
onChange={this.onChange}
>
<TreeNode value="parent 1" title="parent 1" key="0-1">
<TreeNode value="parent 1-0" title="parent 1-0" key="0-1-1">
<TreeNode value="leaf1" title="my leaf" key="random" />
<TreeNode value="leaf2" title="your leaf" key="random1" />
</TreeNode>
<TreeNode value="parent 1-1" title="parent 1-1" key="random2">
<TreeNode value="sss" title={<b style={{ color: '#08c' }}>sss</b>} key="random3" />
</TreeNode>
</TreeNode>
</TreeSelect>
);
}
}
ReactDOM.render(<Demo />, mountNode);
上面的代码是antd官方给出的代码,不过一般我们在处理业务的时候不会这么处理,而是将node中的元素以json的格式绑定到组件上,让组件去做遍历,而不是这种手动去遍历。所以我们会采用其他的方式,官方也给出另外一种方式,就是用json的格式去组装数据:
import { TreeSelect } from 'antd';
const treeData = [
{
title: 'Node1',
value: '0-0',
key: '0-0',
children: [
{
title: 'Child Node1',
value: '0-0-1',
key: '0-0-1',
},
{
title: 'Child Node2',
value: '0-0-2',
key: '0-0-2',
},
],
},
{
title: 'Node2',
value: '0-1',
key: '0-1',
},
];
class Demo extends React.Component {
state = {
value: undefined,
};
onChange = value => {
console.log(value);
this.setState({ value });
};
render() {
return (
<TreeSelect
style={{ width: '100%' }}
value={this.state.value}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
treeData={treeData}
placeholder="Please select"
treeDefaultExpandAll
onChange={this.onChange}
/>
);
}
}
ReactDOM.render(<Demo />, mountNode);
这样就会显示格外的清晰,但是使用官方的代码时,发现个问题,如果在使用到过滤查询的时候
![](https://img-blog.csdnimg.cn/20191224143637265.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NoZW5xa18xMjM=,size_16,color_FFFFFF,t_70)
比如说我去过滤your leaf这个东西,就会过滤不到,
![](https://img-blog.csdnimg.cn/20191224143731639.png)
经过研究,测试,发现,这个组件是根据value值去过滤的而不是title,这就有点不太友好了。
在处理这种json显示的时候,一般我们会把titel作为显示项,把value作为实际下发项。
所以在这里如果想要使用treeselect的时候,我们需要将title和value的值定义成一样的,才会出现根据value值过滤显示对应的title。