在React中使用antd組件中的treeSelect組件焰檩,想要在獲取當(dāng)前選中節(jié)點(diǎn)的所有子節(jié)點(diǎn)鞋拟。在使用onChange方法的時(shí)候叛薯,使用遞歸方法獲得夷磕。
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 TreeChild extends React.Component{
getChild=(arr)=>{
let newArr = []
for(let item = 0;item < arr.length;item++){
newArr.push(arr[item].props.value)
if(arr[item].props.children.length>0){
newArr.push(....getChild(arr[item].props.children))
}
}
return newArr
}
onChange=(value, label, extra)=>{
if(extra.triggerNode){
let arr = this.getChild(extra.triggerNode.props.children)
}
}
render() {
return (
<TreeSelect
style={{ width: '100%' }}
treeData={treeData}
onChange={this.onChange}
/>
);
}
}
就是這樣簡(jiǎn)單恳啥,一開(kāi)始還琢磨不來(lái)遞歸的寫(xiě)法喷面,會(huì)了就很簡(jiǎn)單了星瘾。