ant design 的 tree 如何作为角色中的权限选择之二

在这里插入图片描述
还是接着上一节来 ant design 的 tree 如何作为角色中的权限选择之一

这里先放一下全部代码:

import { useIntl } from '@umijs/max';
import React, { Key, useState } from 'react';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import { Form, Input, Spin, Tree } from 'antd';
import useQueryList from '@/hooks/useQueryList';
import { FormInstance } from 'antd/es/form';
import { Permission } from '@/apiDataStructures/ApiDataStructure';

interface Props {
  form?: FormInstance<any>;
  newRecord?: boolean;
  onFinish: (formData: any) => Promise<void>;
  values?: any;
}

const BasicForm: React.FC<Props> = ({ newRecord, onFinish, values }) => {
  const intl = useIntl();
  const { items: permissionGroups, loading } = useQueryList('/permission-groups/list');

  const [expandedKeys, setExpandedKeys] = useState<Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [checkedKeys, setCheckedKeys] = useState<Key[] | { checked: Key[]; halfChecked: Key[] }>(
    values.permissions?.map((permission: Permission) => `${permission._id}`) ?? [],
  );
  const [selectedKeys, setSelectedKeys] = useState<Key[]>([]);

  const onExpand = (expandedKeysValue: Key[]) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue: Key[] | { checked: Key[]; halfChecked: Key[] }) => {
    setCheckedKeys(checkedKeysValue);
    console.log('checkedKeysValue', checkedKeysValue);
  };

  const onSelect = (selectedKeysValue: Key[]) => {
    setSelectedKeys(selectedKeysValue);
  };

  return (
    <ProForm
      initialValues={{
        ...values,
        permissions: values?.permissions?.map((permission: Permission) => permission._id),
      }}
      onFinish={async (values) => {
        await onFinish({
          ...values,
          permissions: checkedKeys,
        });
      }}
    >
      <ProForm.Group>
        <ProFormText
          rules={[{ required: true, message: intl.formatMessage({ id: 'enter_name' }) }]}
          width="md"
          label={intl.formatMessage({ id: 'name' })}
          name="name"
        />

        <ProForm.Item name="permissions" label={intl.formatMessage({ id: 'permission_choose' })}>
          <Spin spinning={loading}>
            <Tree
              checkable
              onExpand={onExpand}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
              onCheck={onCheck}
              checkedKeys={checkedKeys}
              onSelect={onSelect}
              selectedKeys={selectedKeys}
              treeData={permissionGroups} // Use filtered top-level groups
              fieldNames={{ title: 'name', key: '_id', children: 'children' }}
            />
          </Spin>
        </ProForm.Item>
      </ProForm.Group>

      {!newRecord && (
        <Form.Item name="_id" label={false}>
          <Input type="hidden" />
        </Form.Item>
      )}
    </ProForm>
  );
};

export default BasicForm;

  const { items: permissionGroups, loading } = useQueryList('/permission-groups/list');

这一部分的源码也放出来:

import { useEffect, useState } from 'react';
import { queryList } from '@/services/ant-design-pro/api';

const useQueryList = (url: string, hasPermission = true) => {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false);

  const query = async () => {
    setLoading(true);
    // Only proceed with the API call if the user has permission
    if (hasPermission) {
      const response = (await queryList(url, { pageSize: 10000 })) as any;
      if (response.success) {
        setItems(response.data);
      }
    }
    setLoading(false);
  };

  useEffect(() => {
    query().catch(console.error);
  }, [hasPermission]); // Adding `hasPermission` to the dependency array to re-run the effect if it changes

  return { items, setItems, loading };
};

export default useQueryList;

为什么编辑的时候会填充上选中的状态?

 <ProForm
      initialValues={{
        ...values,
        permissions: values?.permissions?.map((permission: Permission) => permission._id),
      }}
      onFinish={async (values) => {
        await onFinish({
          ...values,
          permissions: checkedKeys,
        });
      }}
    >

主要是这个 initialValues ,permissions 是 那个 name ,对上了就好。

但是提交的时候要把 permissions 带上。

后端的话可以参考我的设计,

我是权限组是有层级的,然后权限组下面有权限

import mongoose, { Document } from 'mongoose';

export interface IPermissionGroup extends Document {
  name: string;
  parent?: IPermissionGroup;
  children?: IPermissionGroup[];
  createdAt?: Date;
  updatedAt?: Date;
}

const permissionGroupSchema = new mongoose.Schema(
  {
    name: { type: String, required: true, unique: true },
    parent: { type: mongoose.Schema.Types.ObjectId, ref: 'PermissionGroup' },
  },
  { timestamps: true },
);

const PermissionGroup = mongoose.model<IPermissionGroup>(
  'PermissionGroup',
  permissionGroupSchema,
);

export default PermissionGroup;

import mongoose, { Document } from 'mongoose';
import { IPermissionGroup } from './permissionGroup';


export interface IPermission extends Document {
  name: string;
  path: string;
  action: string;
  permissionGroup: IPermissionGroup;
  createdAt?: Date;
  updatedAt?: Date;
}

const permissionSchema = new mongoose.Schema({
  name: { type: String, required: true },
  path: { type: String, required: true },
  action: { type: String, required: true },
  permissionGroup: { type: mongoose.Schema.Types.ObjectId, ref: 'PermissionGroup' },
}, { timestamps: true });

const Permission = mongoose.model<IPermission>('Permission', permissionSchema);

export default Permission;

大约是这样的情况,希望对大家有所帮助

我的网站

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Ant DesignTree 组件可以通过 `defaultCheckedKeys` 属性来设置默认选的节点,但是这个属性只能用于静态渲染的情况下,如果需要动态渲染树并且设置默认选节点,可以使用 `checkedKeys` 属性和 `onCheck` 事件来实现。 具体实现方法如下: 1. 在组件的 `state` 定义一个 `checkedKeys` 数组,用于存储当前选的节点。 ```jsx state = { checkedKeys: [], } ``` 2. 在组件的 `componentDidMount` 生命周期,根据需要设置默认选的节点,并将选的节点存储到 `checkedKeys` 数组。 ```jsx componentDidMount() { // 获取需要默认选的节点数据,这里假设是从服务端异步获取的 const checkedNodes = [{key: '1-1'}, {key: '2-2'}]; // 将选的节点的 key 存储到 checkedKeys 数组 const checkedKeys = checkedNodes.map(node => node.key); this.setState({ checkedKeys }); } ``` 3. 在组件的 `render` 方法,将 `checkedKeys` 数组、`onCheck` 事件和其他属性一起传递给 `Tree` 组件。 ```jsx render() { return ( <Tree checkable checkedKeys={this.state.checkedKeys} onCheck={this.handleCheck} // 其他属性 > {/* 树节点 */} </Tree> ); } ``` 4. 在组件定义 `handleCheck` 方法,用于处理节点选状态的变化,并将选的节点的 key 存储到 `checkedKeys` 数组。 ```jsx handleCheck = (checkedKeys) => { this.setState({ checkedKeys }); } ``` 这样,就可以动态设置默认选的节点了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员随风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值