antd tree 选择子节点是否关联父节点

版权声明:如需转载,请注明出处 https://blog.csdn.net/zr15829039341/article/details/82784850

选择某个子菜单时,需要将父菜单也发送过去,后端要判断权限,如果只发子菜单,就做不到匹配,导致父菜单都不会显示在菜单栏。

需要解决的问题是antd tree中,父子节点是受控的,默认如果只选择一个子节点,就只把这一个子节点放进数组,如果选择了父节点下的所有子节点,就会将父节点也放进去。现在需要的是,只选择一个子节点的时候,也将父节点放进去。但是antd tree组件没有提供这个属性。于是自己按照后台给的list数组和checkedKeys进行匹配来生成新的数组。

https://ant.design/components/tree-cn/

做法如下:

在onCheck事件中进行处理,

 [
     {id:1,name:'xx1',parentId:0},
     {id:2,name:'xx2',parentId:1},
     {id:3,name:'xx3',parentId:1},
     {id:4,name:'xx4',parentId:0},
     {id:5,name:'xx5',parentId:4},
     {id:6,name:'xx6',parentId:0},
     {id:7,name:'xx7',parentId:6},
     {id:8,name:'xx8',parentId:6},
     {id:9,name:'xx9',parentId:6}
];

后台给的这个tree的数据是id parentId这样的格式,不是遍历好的对象。所以在生成tree的时候,前端这边遍历了一下生成treeData需要的数据,。

    treeListData = (data,parentId) => {
        var result = [] , temp;
        for(var i in data){
            if(data[i].parentId==parentId){
                result.push(data[i]);
                temp = this.treeListData(data,data[i].id);           
                if(temp.length>0){
                    data[i].children=temp;
                }           
            }       
        }
        return result;
    }

得到如下数据和tree

[
    {id: 1, name: "xx1", parentId: 0, 
    children:[
        {id: 2, name: "xx2", parentId: 1},
        {id: 3, name: "xx3", parentId: 1}
    ]},
    {id: 4, name: "xx4", parentId: 0,
    children:[
        {id: 5, name: "xx5", parentId: 4}
    ]},
    {id: 6, name: "xx6", parentId: 0,
    children:[
        {id: 7, name: "xx7", parentId: 6},
        {id: 8, name: "xx8", parentId: 6},
        {id: 9, name: "xx9", parentId: 6}
    ]}
]

 

需要解决的是当选择某一个子节点的时候,父节点也被放在数组中

方法:

onCheck = (checkedKeys) => {
        const result = data.filter(item => {
            for (let i = 0; i<checkedKeys.length; i++ ) {
                if (checkedKeys[i] === item.id) {
                    return true
                } 
            }       
        }).map(item => item.parentId)
        const checkedKeysResult = Array.from(new Set(result.concat(checkedKeys))).filter(item => item>0)
        this.setState({ 
            checkedKeys,
            checkedKeysResult
        });
}

data是指未经处理从后台接口拿过来的那个数组。

其中,checkedKeys是被选择的子节点的集合,如果只选择了某个子节点 ,在这个数组中是没有父节点的。

checkedKeysResult 是经过处理后的数组,会将子节点对应的父节点通过匹配,去重,放入这个数组中,往后台发送也将是这个数组。

PS:发现这个做法真的是low爆了,

其实官方文档有很好的解决方法:

Tree组件提供的onCheck方法中带了两个参数,其中info这个参数中有一个叫做halfCheckedKeys的数组,它专门存贮的半勾选状态的节点(比如子节点没有勾选完全时,父节点就会被存储到这里)。

    onCheck = (checkedKeys,info) => {
        let checkedKeysResult = [...checkedKeys, ...info.halfCheckedKeys];
        this.setState({ 
            checkedKeys,
            checkedKeysResult
        });
    }

天哪,还是要熟读API呀,好巧秒呀,好喜欢这个方法呀。 

可以参考这个博客

https://blog.csdn.net/qq_32899575/article/details/81458145

猜你喜欢

转载自blog.csdn.net/zr15829039341/article/details/82784850