ant-design-pro的tree组件

文章描述了一个使用AntDesignPro库开发的React应用,实现模块和功能的增删改查,包括分页查询、树形结构展示和表单操作,展示了如何在项目中集成和管理功能列表。
摘要由CSDN通过智能技术生成

可以看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>
        </>
    );

}
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值