55 lines
1.3 KiB
TypeScript
55 lines
1.3 KiB
TypeScript
import { Tree, TreeProps } from 'antd';
|
|
import { DataNode } from 'antd/es/tree';
|
|
import { Key, useEffect, useState } from 'react';
|
|
import { MyProFormFieldProps, MyResponseType } from '../../typings';
|
|
|
|
export function MyTreeCheckable(
|
|
props: {
|
|
api: (data?: any) => Promise<MyResponseType>;
|
|
} & TreeProps<DataNode> &
|
|
MyProFormFieldProps<Key[]>,
|
|
) {
|
|
const [treeData, setTreeData] = useState<DataNode[]>([]);
|
|
|
|
const processTree = (item: any): DataNode => {
|
|
return {
|
|
...item,
|
|
key: item.id,
|
|
title: item.id + '_' + item.name,
|
|
children: item.children?.map(processTree),
|
|
};
|
|
};
|
|
|
|
useEffect(() => {
|
|
props.api?.({ guard_name: process.env.GUARD_NAME }).then((res: any) => {
|
|
const data = res.data?.map(processTree);
|
|
setTreeData(data);
|
|
});
|
|
}, []);
|
|
|
|
const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {
|
|
console.log('onCheck', checkedKeys, info);
|
|
const ids: Key[] = [];
|
|
info.checkedNodes?.forEach((item) => {
|
|
if (item.children?.length === 0) {
|
|
ids.push(item.key);
|
|
}
|
|
});
|
|
console.log('ids', ids);
|
|
props.onChange?.(ids);
|
|
};
|
|
|
|
return (treeData?.length ?? 0) > 0 ? (
|
|
<Tree
|
|
checkable
|
|
defaultExpandAll
|
|
treeData={treeData}
|
|
onCheck={onCheck}
|
|
checkedKeys={props.value ?? []}
|
|
{...props}
|
|
/>
|
|
) : (
|
|
<></>
|
|
);
|
|
}
|