import React, { Component } from "react";
import { Button, message, Modal, Spin, Table, Checkbox, Collapse, } from "antd";
import $ from "jquery/src/ajax";
const params = {
"authTree": [
{
"authName": "商场数据分析",
"authId": 1,
"children": [{
"authName": "数据概览",
"authId": 3,
},
{
"authName": "数据概览2",
"authId": 4,
}]
},
{
"authName": "商场数据分析2",
"authId": 2,
"children": [{
"authName": "数据概览3",
"authId": 5,
}]
}
],
"checkedList": [6, 7, 11]
}
class Cascaders extends Component {
constructor(props) {
super(props);
this.state = {
visible: false,
authTree: [],
checkedList: [],
};
this.itemHandle = this.itemHandle.bind(this);
}
componentDidMount() {
// 后端返回的数据,转成前端要用的数据保存页面使用
const authTree = params.authTree;
const checkedList = params.checkedList;
this.setState({
authTree,
checkedList,
}, () => {
this.authTreeFun();
});
}
// 转成前端要用的数据
authTreeFun() {
const checkedList = this.state.checkedList;
checkedList.forEach((item) => {
this.itemHandle(item);
});
}
// 代码三级联动核心就在这里
itemHandle(authId, checked = true) {
const authTree = [...this.state.authTree];
authTree.forEach((item1) => {
if (item1.authId === authId) {
item1.checked = checked;
if (item1.children) {
item1.children.forEach((item2) => {
item2.checked = checked;
// if (item2.children) {
// item2.children.forEach((item3) => {
// item3.checked = checked;
// });
// }
});
}
} else {
// 反向思路: 保存子选项框的个数, 子选项选中就-1, 等于0说明都选中了, 父选项就勾上
let temp1 = item1.children.length;
item1.children.forEach((item2) => {
if (item2.authId === authId) {
item2.checked = checked;
// if (item2.children) {
// item2.children.forEach((item3) => {
// item3.checked = checked;
// });
// }
} else {
// let temp2 = item2.children.length;
// item2.children.forEach((item3) => {
// if (item3.authId === authId) {
// item3.checked = checked;
// }
// item3.checked ? temp2 -= 1 : temp2;
// });
// temp2 === 0 ? item2.checked = true : item2.checked = false;
}
// 选中-1, 未选中不动
item2.checked ? temp1 -= 1 : temp1;
});
// 长度是0, 父选项框就勾选
temp1 === 0 ? item1.checked = true : item1.checked = false;
}
});
this.setState({
authTree,
});
}
render() {
const { Panel } = Collapse;
const authTreeMap = this.state.authTree.map((item1) => (
// Panel是手风琴