CollectionField

字段的 schema 分为 2 部分,一部分在 schema 中,一部分在 collection 中。例如:

1const schema = {
2  properties: {
3    username: {
4      'x-component': 'CollectionField',
5      'x-decorator': 'FormItem',
6    },
7  }
8}
9
10const collection = {
11  fields: [
12    {
13      type: 'string',
14      name: 'username',
15      interface: 'input',
16      uiSchema: {
17        title: 'UserName',
18        type: 'string',
19        'x-component': 'Input',
20        required: true,
21        description: 'description',
22      },
23    }
24  ],
25}

两者通过 name: username 联系起来,CollectionField 会自动读取 schema name 属性,并根据 name 属性查找 collection 中对应的 uiSchema 属性,然后拼接到 schema 中,进行渲染。

这样做的好处是,对于同一个字段创建的内容,可以在不同的地方共享同一个 schema,当 schema 变化时,只需要修改一处即可。比如通过上面的 title: "UserName" 假设变化 title: "Name" 则所有使用到此字段的地方都会变化。

1. CollectionFieldOptions

字段的配置项。

1interface CollectionFieldOptions {
2  name?: any;
3  collectionName?: string;
4  sourceKey?: string;
5  uiSchema?: ISchema;
6  target?: string;
7
8  [key: string]: any;
9}

普通字段和关系字段

字段有 2 种情况,一种是普通字段,一种是关系字段。

关系字段是指,字段的值是另一个 collection 的数据,例如 usersroles 两个 collection,users 中有一个字段 roles,其值是 roles collection 的数据,那么 roles 就是一个关系字段。

普通字段的示例如下:

1{
2  "key": "t09bauwm0wb",
3  "name": "email",
4  "type": "string",
5  "interface": "email",
6  "description": null,
7  "collectionName": "users",
8  "parentKey": null,
9  "reverseKey": null,
10  "unique": true,
11  "uiSchema": {
12    "type": "string",
13    "title": "{{t('Email')}}",
14    "x-component": "Input",
15    "x-validator": "email",
16    "required": true
17  }
18}

关系字段的示例如下:

1{
2  "key": "fds09bauwm",
3  "name": "roles",
4  "type": "belongsToMany",
5  "interface": "m2m",
6  "description": null,
7  "collectionName": "users",
8  "parentKey": null,
9  "reverseKey": null,
10  "target": "roles",
11  "foreignKey": "userId",
12  "otherKey": "roleName",
13  "onDelete": "CASCADE",
14  "sourceKey": "id",
15  "targetKey": "name",
16  "through": "rolesUsers",
17  "uiSchema": {
18    "type": "array",
19    "title": "{{t('Roles')}}",
20    "x-component": "AssociationField",
21    "x-component-props": {
22      "multiple": true,
23      "fieldNames": {
24        "label": "title",
25        "value": "name"
26      }
27    }
28  }
29}

全部字段说明

  • name:字段名称
  • collectionName:数据表名称
  • sourceKey:当字段为关系字段时,对应的关系字段名称。

2. Hooks

useCollectionField()

用于获取字段信息。

1const collection = {
2  fields: [
3    {
4      type: 'string',
5      name: 'username',
6      interface: 'input',
7      uiSchema: {
8        title: 'UserName',
9        type: 'string',
10        'x-component': 'Input',
11        required: true,
12        description: 'description1',
13      } as ISchema,
14    }
15  ],
16}
17
18const { uiSchema } = useCollectionField()
19const required = uiSchema?.required

其通常在 SchemaSettings 中使用,用来获取和修改字段的属性。