Bootstrap

ant-design-pro的tree组件

可以看ant-design-pro文档
在这里插入图片描述

效果:
在这里插入图片描述

import React, { useState, useEffect } from "react";
import { PlusOutlined, EditOutlined, DeleteOutlined, CloseOutlined, CheckOutlined } from '@ant-design/icons';
import { Modal, Tree, Input, Form, Button, Space, message } from 'antd';
import {
    querySysModule, addSysFunction, deleteSysFunction, querySysFunctionById, updateSysFunction
} from "@/services/uav-platform/featureApi";

type QuerySysModuleList = {
    pageIndex: string | number;
    pageSize: string | number;
}
type SysModule = {
    isLeaf: boolean;
    children?: string
    sysFunctionVOList?: string;
    key?: string;
    sysModuleId?: string;
    title?: string;
    moduleName?: string;
    moduleId?: string
    SysModule?: string
    functionName?: string
    remark?: string,
    functionPath?: string,
    functionId?: string
    isEditable?: boolean

}
//input 
type FieldType = {
    functionName?: string;
    remark?: string;
    functionPath?: string;
    moduleId?: string;
};

// tree
const { TreeNode } = Tree;

interface DataNode {
    title: string;
    key: string;
    isLeaf?: boolean;
    children?: DataNode[];
    moduleName?: string;
    moduleId?: string
    SysModule?: string
    functionName?: string
    remark?: string,
    functionPath?: string,
    functionId?: string
    isEditable?: boolean
}

const initTreeData: DataNode[] = [
    { title: `111`, key: '0' ,children:[{title: `111`, key: '0' ,}]},
    { title: 'Expand to load', key: '1' },
    { title: 'Tree Node', key: '2', isLeaf: true },
];
const updateTreeData = (list: DataNode[], key: React.Key, children: DataNode[]): DataNode[] =>
    list.map((node) => {
        if (node.key === key) {
            return {
                ...node,
                children,
            };
        }
        if (node.children) {
            return {
                ...node,
                children: updateTreeData(node.children, key, children),
            };
        }
        return node;
    });
export default () => {
    //提示
    const [messageApi, contextHolder] = message.useMessage();
    const [treeData, setTreeData] = useState(initTreeData);
    const [featureData, setfeatureData] = useState(treeData);
    const [pageIndex, setPageIndex] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(10);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [moduleId, setModuleId] = useState<number>();
    const [functionId, setFunctionId] = useState<number>();
    const [title, setTitle] = useState('新增');
    const [form] = Form.useForm();
    //分页查询功能信息
    const fetchModuleList = async (values: QuerySysModuleList) => {
        // 获取所有模块
        const res = await querySysModule({ ...values })

        console.log('res分页查询功能信息:', res);
        const { arr } = res
        const _treeData: DataNode[] = arr.map((item: SysModule, index: number) => {
            item.title = item.moduleName
            item.key = item.sysModuleId
            return item
        })
        console.log('_treeData:',_treeData);
        
        setTreeData(_treeData);
        setfeatureData(_treeData)
    }
    useEffect(() => {
        fetchModuleList({ pageIndex, pageSize })
    }, [initTreeData, moduleId, functionId])

    //新增
    const onAdd = (key: number) => {
        console.log('onAdd', key);
        setModuleId(key)存储模块id
        if (!key) {
            console.log('!key');
            return
        }
        setIsModalOpen(true);
    };

    //删除
    const onDelete = (key: any) => {
        console.log('onDelete', key);
        deleteSysFunction(key).then((res) => {
            if (res.msg === 'ok') {
                messageApi.open({
                    type: 'success',
                    content: '删除用户成功',
                });
                fetchModuleList({ pageIndex, pageSize })
                // window.location.reload() // 强制页面刷新

            }
        })
    };
    //编辑
    const onEdit = (key: any) => {
        console.log('key:', key);
        setFunctionId(key) //存储功能id
        setTitle('编辑') //弹框名字改为编辑
        setIsModalOpen(true); //打开弹框
        querySysFunctionById(key).then((res) => {
            console.log('res详情:', res);
            const { data } = res
            setModuleId(data.moduleId)//存储模块id
            form.setFieldsValue(data)
        })
    };
    //tree
    const onLoadData = ({ key, children, sysFunctionVOList }: any) =>
        new Promise<void>((resolve) => {
            if (children) {
                children = sysFunctionVOList
                children.forEach((item: SysModule) => {
                    console.log('item:', item);
                    item.title = item.functionName
                    item.isLeaf = true
                });
                setTreeData((origin) =>
                    updateTreeData(origin, key, sysFunctionVOList),
                );
                setfeatureData((origin) =>
                    updateTreeData(origin, key, sysFunctionVOList),
                )
                resolve();
                return;
            }
            setTimeout(() => {
                setTreeData((origin) =>
                    updateTreeData(origin, key, sysFunctionVOList),
                );
                setfeatureData((origin) =>
                    updateTreeData(origin, key, sysFunctionVOList),
                )
                resolve();
            }, 1000);
        });

    //新增-编辑保存
    const onFinish = (values: any) => {
        if (title === '新增') {
            values.moduleId = moduleId
            console.log('Success:', values);
            addSysFunction({ ...values }).then((res) => {
                console.log('res新增', res);
                if (res.msg === 'ok') {
                    messageApi.open({
                        type: 'success',
                        content: '新增权限成功',
                    });
                    fetchModuleList({ pageIndex, pageSize })

                    // window.location.reload() // 强制页面刷新
                }
            })
        } else {
            values.moduleId = moduleId
            values.functionId = functionId
            console.log('Success:', values);
            updateSysFunction({ ...values }).then((res) => {
                console.log('res编辑', res);
                if (res.msg === 'ok') {
                    messageApi.open({
                        type: 'success',
                        content: '编辑权限成功',
                    });
                    fetchModuleList({ pageIndex, pageSize })
                    // window.location.reload() // 强制页面刷新
                }

            })
        }

        setIsModalOpen(false);
        form.resetFields();
    };

    //modal的方法 
    const handleCancel = () => {
        setIsModalOpen(false);
        fetchModuleList({ pageIndex, pageSize })
    };

    const renderTreeNodes = (data: any) => {
        let nodeArr = data.map((item: any) => {
            item.title = (
                <div>
                    <span>
                        {item.moduleName ? item.moduleName : item.functionName}</span>
                    <span>
                        {item.moduleName ? <PlusOutlined style={{ marginLeft: 10 }}
                            onClick={() => onAdd(item.sysModuleId)} /> : <></>}
                        {item.functionName ? <EditOutlined style={{ marginLeft: 10 }}
                            onClick={() => onEdit(item.sysModuleId || item.functionId)} /> : <></>}
                        <DeleteOutlined style={{ marginLeft: 10 }} onClick={() => onDelete(item.sysModuleId || item.functionId)} />
                    </span>
                </div>
            );

            if (item.sysFunctionVOList) {
                return (
                    <TreeNode title={item.title} key={item.sysModuleId}>
                        {renderTreeNodes(item.sysFunctionVOList)}
                    </TreeNode>
                );
            }

            return <TreeNode title={item.title} key={item.sysModuleId} />;
        });

        return nodeArr;
    };

    return (
        <>
            {contextHolder}
            <Modal title={title} open={isModalOpen} onCancel={handleCancel} footer={null}>

                <Form
                    name="basic"
                    form={form}
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ maxWidth: 600 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    autoComplete="off"
                >
                    <Form.Item<FieldType>
                        label="功能名称"
                        name="functionName"
                        rules={[{ required: true }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item<FieldType>
                        label="备注"
                        name="remark"
                        rules={[{ required: true }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item<FieldType>
                        label="路径"
                        name="functionPath"
                        rules={[{ required: true }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Space>
                            <Button type="primary" htmlType="submit"  >
                                确定
                            </Button>
                            <Button htmlType="button" onClick={handleCancel}>
                                取消
                            </Button>
                        </Space>
                    </Form.Item>

                </Form>
            </Modal >

            <Tree loadData={onLoadData} treeData={treeData} fieldNames={ {title: 'title', key: 'key', children: 'sysFunctionVOList'} }> 
                {treeData?.length && renderTreeNodes(featureData)}
            </Tree>
        </>
    );

}
;