Formily ArrayCollapse 折叠面板组件完全指南:Schema 数组表单的折叠交互与联动方案

原创2026-09-22 20:05:111,614 阅读
文章标签:前端UI组件

Formily ArrayCollapse 折叠面板组件完全指南:Schema 数组表单的折叠交互与联动方案

折叠面板(ArrayCollapse)是 Formily 面向"每行字段数量较多、字段间联动较多"场景提供的 Schema 数组渲染组件:每个数组项以可展开/收起的面板呈现,天然适合复杂对象数组的录入。本文以 Formily 2.x(@formily/antd)为例,完整讲解 ArrayCollapse 的 Markup Schema 与 JSON Schema 两种写法、内置操作子组件、Effects/Reactions 联动方案及全部扩展 API,并结合 ArrayCollapse 源码 与 ArrayBase 底层实现 剖析其折叠状态管理与数组操作原理。读完本文,你将能直接用 Schema 搭建"多字段、多联动、可增删排序"的折叠数组表单。

注意:ArrayCollapse 只适用于 Schema 场景(Markup Schema 或 JSON Schema),不支持纯 @formily/react 的 JSX 手写模式。

一、核心概念:为什么选择 ArrayCollapse

当一个数组项的字段数量较多(例如一个"收货地址"包含省、市、区、街道、电话等多个字段),或者数组项之间存在强联动逻辑时,ArrayCollapse 是最合适的容器组件:

  • 每个数组项对应一个 antd Collapse 折叠面板,默认只展开部分面板,避免页面被大段表单撑满;
  • 通过 defaultOpenPanelCount 控制初始展开面板数量,配合折叠交互缓解长表单的视觉压力;
  • 面板头部内置索引(Index)、错误徽标(Badge),面板操作区(extra)内置删除、上移、下移按钮,面板底部可放置"添加条目"按钮;
  • 数组的增、删、上移、下移由 Formily 的 ArrayField 模型驱动(见 ArrayField.ts),操作数据的同时会同步维护字段状态树。

从 index.tsx 可以看到,组件接收 defaultOpenPanelCount = 5 作为默认值,并在字段尚未被用户修改(!field.modified)时根据数据源长度自动计算初始展开的激活面板:

const takeDefaultActiveKeys = (dataSourceLength, defaultOpenPanelCount) => {
  if (dataSourceLength < defaultOpenPanelCount) return range(dataSourceLength)
  return range(defaultOpenPanelCount)
}

即:数据条数少于设定值时全部展开,否则只展开前 N 个面板。

二、Markup Schema 案例:字符串数组与对象数组

下面的完整案例演示了三种数组形态:string_array(字符串数组 + 手风琴模式)、array(对象数组)、string_array_unshift(新增条目插到数组头部)。请将本案例代码置于任意 React 页面中,并确保已安装依赖:

npm install @formily/core @formily/react @formily/antd antd
import React from 'react'
import {
  FormItem,
  Input,
  ArrayCollapse,
  FormButtonGroup,
  Submit,
} from '@formily/antd'
import { createForm } from '@formily/core'
import { FormProvider, createSchemaField } from '@formily/react'
import { Button } from 'antd'

const SchemaField = createSchemaField({
  components: {
    FormItem,
    Input,
    ArrayCollapse,
  },
})

const form = createForm()

export default () => {
  return (
    <FormProvider form={form}>
      <SchemaField>
        <SchemaField.Array
          name="string_array"
          maxItems={3}
          x-decorator="FormItem"
          x-component="ArrayCollapse"
          x-component-props={{
            accordion: true,
            defaultOpenPanelCount: 3,
          }}
        >
          <SchemaField.Void
            x-component="ArrayCollapse.CollapsePanel"
            x-component-props={{
              header: '字符串数组',
            }}
          >
            <SchemaField.Void x-component="ArrayCollapse.Index" />
            <SchemaField.String
              name="input"
              x-decorator="FormItem"
              title="Input"
              required
              x-component="Input"
            />
            <SchemaField.Void x-component="ArrayCollapse.Remove" />
            <SchemaField.Void x-component="ArrayCollapse.MoveUp" />
            <SchemaField.Void x-component="ArrayCollapse.MoveDown" />
          </SchemaField.Void>
          <SchemaField.Void
            x-component="ArrayCollapse.Addition"
            title="添加条目"
          />
        </SchemaField.Array>
        <SchemaField.Array
          name="array"
          maxItems={3}
          x-decorator="FormItem"
          x-component="ArrayCollapse"
        >
          <SchemaField.Object
            x-component="ArrayCollapse.CollapsePanel"
            x-component-props={{
              header: '对象数组',
            }}
          >
            <SchemaField.Void x-component="ArrayCollapse.Index" />
            <SchemaField.String
              name="input"
              x-decorator="FormItem"
              title="Input"
              required
              x-component="Input"
            />
            <SchemaField.Void x-component="ArrayCollapse.Remove" />
            <SchemaField.Void x-component="ArrayCollapse.MoveUp" />
            <SchemaField.Void x-component="ArrayCollapse.MoveDown" />
          </SchemaField.Object>
          <SchemaField.Void
            x-component="ArrayCollapse.Addition"
            title="添加条目"
          />
        </SchemaField.Array>
        <SchemaField.Array
          name="string_array_unshift"
          maxItems={3}
          x-decorator="FormItem"
          x-component="ArrayCollapse"
          x-component-props={{
            defaultOpenPanelCount: 8,
          }}
        >
          <SchemaField.Void
            x-component="ArrayCollapse.CollapsePanel"
            x-component-props={{
              header: '字符串数组',
            }}
          >
            <SchemaField.Void x-component="ArrayCollapse.Index" />
            <SchemaField.String
              name="input"
              x-decorator="FormItem"
              title="Input"
              required
              x-component="Input"
            />
            <SchemaField.Void x-component="ArrayCollapse.Remove" />
            <SchemaField.Void x-component="ArrayCollapse.MoveUp" />
            <SchemaField.Void x-component="ArrayCollapse.MoveDown" />
          </SchemaField.Void>
          <SchemaField.Void
            x-component="ArrayCollapse.Addition"
            title="添加条目(unshift)"
            x-component-props={{
              method: 'unshift',
            }}
          />
        </SchemaField.Array>
      </SchemaField>
      <FormButtonGroup>
        <Button
          onClick={() => {
            form.setInitialValues({
              array: Array.from({ length: 10 }).map(() => ({
                input: 'default value',
              })),
              string_array: Array.from({ length: 10 }).map(
                () => 'default value'
              ),
              string_array_unshift: Array.from({ length: 10 }).map(
                () => 'default value'
              ),
            })
          }}
        >
          加载默认数据
        </Button>
        <Submit onSubmit={console.log}>提交</Submit>
      </FormButtonGroup>
    </FormProvider>
  )
}

关键点拆解:

  • maxItems={3} 限制数组最大长度,新增条目超过 3 条时 Addition 按钮将不可用;
  • x-component="ArrayCollapse" 声明容器组件,x-decorator="FormItem" 让整个数组块具备 FormItem 的布局与校验展示能力;
  • accordion: true 表示手风琴模式,同一时刻只允许展开一个面板;
  • defaultOpenPanelCount: 3 与 defaultOpenPanelCount: 8 演示了初始展开数量的差异——即使"加载默认数据"一次性填充 10 条,初始也只会展开设定数量的面板;
  • x-component="ArrayCollapse.CollapsePanel" 声明面板外壳:字符串数组用 Void 承载,对象数组用 Object 承载,两者渲染结果一致,但对象数组在数据模型中会产出 { input: 'default value' } 这样的对象元素;
  • ArrayCollapse.Addition 的 method: 'unshift' 让新增元素插入数组头部而不是尾部。

数组操作的数据模型支撑

Addition/Remove/MoveUp/MoveDown 等操作最终调用的是 ArrayField 提供的实例方法。例如 ArrayBase.Addition 内部会依据 method 选择 array.field.unshift(...) 或 array.field.push(...),而 ArrayField.unshift 会先通过 spliceArrayState 同步字段状态树(确保字段地址正确平移),再执行 this.value.unshift(...items) 并触发 onInput,最终驱动 UI 重渲染与折叠面板的展开状态更新。

同样地,Remove 对应 array.field.remove(index),MoveUp/MoveDown 对应 array.field.moveUp(index) / array.field.moveDown(index)(见 ArrayField.ts)。此外 ArrayField 还提供了 insert、pop、shift、move 等方法,供你在自定义操作按钮时直接使用。

三、JSON Schema 案例:用纯 JSON 描述折叠数组

JSON Schema 写法与 Markup Schema 等价,适合后端下发表单配置、表单动态渲染等场景。以下 schema 与上文案例行为一致,还额外演示了 onAdd 回调:

import React from 'react'
import {
  FormItem,
  Input,
  ArrayCollapse,
  FormButtonGroup,
  Submit,
} from '@formily/antd'
import { createForm } from '@formily/core'
import { FormProvider, createSchemaField } from '@formily/react'

const SchemaField = createSchemaField({
  components: {
    FormItem,
    Input,
    ArrayCollapse,
  },
})

const form = createForm()

const schema = {
  type: 'object',
  properties: {
    string_array: {
      type: 'array',
      'x-component': 'ArrayCollapse',
      'x-component-props': {
        onAdd: (index: number) => {
          console.log('Adding ' + index + ' item')
        },
      },
      maxItems: 3,
      'x-decorator': 'FormItem',
      items: {
        type: 'void',
        'x-component': 'ArrayCollapse.CollapsePanel',
        'x-component-props': {
          header: '字符串数组',
        },
        properties: {
          index: {
            type: 'void',
            'x-component': 'ArrayCollapse.Index',
          },
          input: {
            type: 'string',
            'x-decorator': 'FormItem',
            title: 'Input',
            required: true,
            'x-component': 'Input',
          },
          remove: {
            type: 'void',
            'x-component': 'ArrayCollapse.Remove',
          },
          moveUp: {
            type: 'void',
            'x-component': 'ArrayCollapse.MoveUp',
          },
          moveDown: {
            type: 'void',
            'x-component': 'ArrayCollapse.MoveDown',
          },
        },
      },
      properties: {
        addition: {
          type: 'void',
          title: '添加条目',
          'x-component': 'ArrayCollapse.Addition',
        },
      },
    },
    array: {
      type: 'array',
      'x-component': 'ArrayCollapse',
      maxItems: 3,
      'x-decorator': 'FormItem',
      items: {
        type: 'object',
        'x-component': 'ArrayCollapse.CollapsePanel',
        'x-component-props': {
          header: '对象数组',
        },
        properties: {
          index: {
            type: 'void',
            'x-component': 'ArrayCollapse.Index',
          },
          input: {
            type: 'string',
            'x-decorator': 'FormItem',
            title: 'Input',
            required: true,
            'x-component': 'Input',
          },
          remove: {
            type: 'void',
            'x-component': 'ArrayCollapse.Remove',
          },
          moveUp: {
            type: 'void',
            'x-component': 'ArrayCollapse.MoveUp',
          },
          moveDown: {
            type: 'void',
            'x-component': 'ArrayCollapse.MoveDown',
          },
        },
      },
      properties: {
        addition: {
          type: 'void',
          title: '添加条目',
          'x-component': 'ArrayCollapse.Addition',
        },
      },
    },
    array_unshift: {
      type: 'array',
      'x-component': 'ArrayCollapse',
      maxItems: 3,
      'x-decorator': 'FormItem',
      items: {
        type: 'object',
        'x-component': 'ArrayCollapse.CollapsePanel',
        'x-component-props': {
          header: '对象数组',
        },
        properties: {
          index: {
            type: 'void',
            'x-component': 'ArrayCollapse.Index',
          },
          input: {
            type: 'string',
            'x-decorator': 'FormItem',
            title: 'Input',
            required: true,
            'x-component': 'Input',
          },
          remove: {
            type: 'void',
            'x-component': 'ArrayCollapse.Remove',
          },
          moveUp: {
            type: 'void',
            'x-component': 'ArrayCollapse.MoveUp',
          },
          moveDown: {
            type: 'void',
            'x-component': 'ArrayCollapse.MoveDown',
          },
        },
      },
      properties: {
        addition: {
          type: 'void',
          title: '添加条目(unshift)',
          'x-component': 'ArrayCollapse.Addition',
          'x-component-props': {
            method: 'unshift',
          },
        },
      },
    },
  },
}

export default () => {
  return (
    <FormProvider form={form}>
      <SchemaField schema={schema} />
      <FormButtonGroup>
        <Submit onSubmit={console.log}>提交</Submit>
      </FormButtonGroup>
    </FormProvider>
  )
}

JSON Schema 与 Markup Schema 的字段映射关系:

Markup Schema 片段 JSON Schema 等价表达
<SchemaField.Array name="array" maxItems={3} /> { type: 'array', maxItems: 3 }
x-component="ArrayCollapse" 'x-component': 'ArrayCollapse'
x-component-props={{...}} 'x-component-props': {...}
<SchemaField.Object x-component="ArrayCollapse.CollapsePanel"> items: { type: 'object', 'x-component': 'ArrayCollapse.CollapsePanel' }
面板内的子字段 items.properties
面板外的 Addition 数组节点自身的 properties.addition

四、Effects 联动案例:主动联动与被动联动

当折叠面板内的字段需要互相联动时,Formily 提供两种 effects 写法。本案例中:AA 输入 123 时隐藏 BB(主动联动),CC 输入 123 时隐藏 DD(被动联动)。

import React from 'react'
import {
  FormItem,
  Input,
  ArrayCollapse,
  FormButtonGroup,
  Submit,
} from '@formily/antd'
import { createForm, onFieldChange, onFieldReact } from '@formily/core'
import { FormProvider, createSchemaField } from '@formily/react'

const SchemaField = createSchemaField({
  components: {
    FormItem,
    Input,
    ArrayCollapse,
  },
})

const form = createForm({
  effects: () => {
    // 主动联动模式
    onFieldChange('array.*.aa', ['value'], (field, form) => {
      form.setFieldState(field.query('.bb'), (state) => {
        state.visible = field.value != '123'
      })
    })
    // 被动联动模式
    onFieldReact('array.*.dd', (field) => {
      field.visible = field.query('.cc').get('value') != '123'
    })
  },
})

export default () => {
  return (
    <FormProvider form={form}>
      <SchemaField>
        <SchemaField.Array
          name="array"
          maxItems={3}
          x-component="ArrayCollapse"
          x-decorator="FormItem"
          x-component-props={{
            title: '对象数组',
          }}
        >
          <SchemaField.Object
            x-component="ArrayCollapse.CollapsePanel"
            x-component-props={{
              header: '对象数组',
            }}
          >
            <SchemaField.Void x-component="ArrayCollapse.Index" />
            <SchemaField.String
              name="aa"
              x-decorator="FormItem"
              title="AA"
              required
              description="AA输入123时隐藏BB"
              x-component="Input"
            />
            <SchemaField.String
              name="bb"
              x-decorator="FormItem"
              title="BB"
              required
              x-component="Input"
            />
            <SchemaField.String
              name="cc"
              x-decorator="FormItem"
              title="CC"
              required
              description="CC输入123时隐藏DD"
              x-component="Input"
            />
            <SchemaField.String
              name="dd"
              x-decorator="FormItem"
              title="DD"
              required
              x-component="Input"
            />
            <SchemaField.Void x-component="ArrayCollapse.Remove" />
            <SchemaField.Void x-component="ArrayCollapse.MoveUp" />
            <SchemaField.Void x-component="ArrayCollapse.MoveDown" />
          </SchemaField.Object>
          <SchemaField.Void
            x-component="ArrayCollapse.Addition"
            title="添加条目"
          />
        </SchemaField.Array>
      </SchemaField>
      <FormButtonGroup>
        <Submit onSubmit={console.log}>提交</Submit>
      </FormButtonGroup>
    </FormProvider>
  )
}

主动联动:onFieldChange

onFieldChange('array.*.aa', <a href="https://link.gitcode.com/i/8900ad8a3c3a6dcce3a0e89e8c5a1c47" target="_blank">'value'], cb) 订阅所有数组项(* 通配任意索引)中 aa 字段的 value 变化,变化时通过 field.query('.bb') 相对地址定位同面板内的 bb 字段并修改其 visible。其底层实现位于 [onFieldEffects.ts:第三个参数可省略 watches,省略时默认监听 ['value']。

被动联动:onFieldReact

onFieldReact('array.*.dd', cb) 会在 dd 字段初始化时注册一个 autorun 响应式订阅(见 onFieldEffects.ts),回调中读取的 field.query('.cc').get('value') 会成为响应式依赖——一旦 CC 值变化,dd 的 visible 会自动重算,无需手动订阅事件。这种"由依赖驱动、声明式描述"的模式更适合规则稳定、依赖清晰的场景。

五、JSON Schema 联动案例:基于 x-reactions 的声明式联动

如果不想写 effects,可以将联动规则直接内嵌进 JSON Schema,通过 x-reactions 实现。下面的案例中:aa 输入不等于 123 时,bb 被禁用并保持标题 "BB";等于 123 时,bb 标题变为 "Changed" 且恢复可编辑。

import React from 'react'
import {
  FormItem,
  Input,
  ArrayCollapse,
  FormButtonGroup,
  Submit,
} from '@formily/antd'
import { createForm } from '@formily/core'
import { FormProvider, createSchemaField } from '@formily/react'

const SchemaField = createSchemaField({
  components: {
    FormItem,
    Input,
    ArrayCollapse,
  },
})

const form = createForm()

const schema = {
  type: 'object',
  properties: {
    array: {
      type: 'array',
      'x-component': 'ArrayCollapse',
      maxItems: 3,
      title: '对象数组',
      items: {
        type: 'object',
        'x-component': 'ArrayCollapse.CollapsePanel',
        'x-component-props': {
          header: '对象数组',
        },
        properties: {
          index: {
            type: 'void',
            'x-component': 'ArrayCollapse.Index',
          },
          aa: {
            type: 'string',
            'x-decorator': 'FormItem',
            title: 'AA',
            required: true,
            'x-component': 'Input',
            description: '输入123',
          },
          bb: {
            type: 'string',
            title: 'BB',
            required: true,
            'x-decorator': 'FormItem',
            'x-component': 'Input',
            'x-reactions': [
              {
                dependencies: ['.aa'],
                when: "{{$deps[0] != '123'}}",
                fulfill: {
                  schema: {
                    title: 'BB',
                    'x-disabled': true,
                  },
                },
                otherwise: {
                  schema: {
                    title: 'Changed',
                    'x-disabled': false,
                  },
                },
              },
            ],
          },
          remove: {
            type: 'void',
            'x-component': 'ArrayCollapse.Remove',
          },
          moveUp: {
            type: 'void',
            'x-component': 'ArrayCollapse.MoveUp',
          },
          moveDown: {
            type: 'void',
            'x-component': 'ArrayCollapse.MoveDown',
          },
        },
      },
      properties: {
        addition: {
          type: 'void',
          title: '添加条目',
          'x-component': 'ArrayCollapse.Addition',
        },
      },
    },
  },
}

export default () => {
  return (
    <FormProvider form={form}>
      <SchemaField schema={schema} />
      <FormButtonGroup>
        <Submit onSubmit={console.log}>提交</Submit>
      </FormButtonGroup>
    </FormProvider>
  )
}

x-reactions 规则说明:

  • dependencies: ['.aa']:以相对路径声明依赖同面板内的 aa 字段;
  • when: "{{$deps[0] != '123'}}":模板表达式,$deps 按声明顺序注入依赖值;
  • fulfill / otherwise:条件成立与不成立时分别执行的 schema 修改,这里演示了动态修改标题与禁用状态。

六、完整 API 参考

ArrayCollapse 由容器组件与若干静态子组件构成,全部通过 @formily/antd 导出(见 packages/antd/src/index.ts),并在组件内部通过 ArrayBase.mixin(ArrayCollapse) 注入子组件(见 array-collapse/index.tsx)。

ArrayCollapse

容器组件,继承 antd Collapse 的全部 props(accordion、activeKey、onChange、bordered 等),另扩展:

属性名 类型 描述 默认值
defaultOpenPanelCount number 数据源加载后默认展开的面板数量 5

从源码 index.tsx 可知,IArrayCollapseProps extends CollapseProps 且新增 defaultOpenPanelCount。组件还透传 ArrayBase 的回调:onAdd、onCopy、onRemove、onMoveUp、onMoveDown(均为 (index: number) => void)。

ArrayCollapse.CollapsePanel

面板外壳(虚拟节点),用于声明折叠面板的 header 等 antd Collapse.Panel 属性。它本身只渲染 Fragment(见 index.tsx),真正的面板由 ArrayCollapse 内部根据数据源循环渲染。面板头部文案的取值优先级为:当前数组项面板的 componentProps.header > items schema 的 x-component-props.header > 数组字段的 title(见 index.tsx)。其余属性参考 antd Collapse 面板文档。

ArrayCollapse.Addition

添加按钮,基于 antd Button(type="dashed"、block)。扩展属性:

属性名 类型 描述 默认值
title ReactText 文案 —
method 'push' | 'unshift' 添加方式 'push'
defaultValue any 新条目的默认值 依据 items schema 自动推导

实现细节(array-base/index.tsx):

  • method='unshift' 时调用 array.field.unshift(defaultValue) 并回调 onAdd(0);否则调用 array.field.push(defaultValue) 并回调 onAdd(value.length - 1);
  • defaultValue 未传时,会依据 items 的 schema 类型自动推导:数组类型返回 <a href="https://link.gitcode.com/i/2ed590e13914fe1055f7d356e9281d31" target="_blank">]、对象类型返回 {}、void 类型则递归查找第一个有效子字段默认值(见 [getSchemaDefaultValue);
  • title 属性可以接收 Field 模型中的 title 映射,即 schema 字段上设置的 title 同样生效(渲染时使用 props.title || self.title);
  • 使用 onClick={e => e.preventDefault()} 可禁用默认的添加行为(源码中 if (e.defaultPrevented) return);
  • 当字段 pattern 不为 editable / disabled 时按钮不渲染。

ArrayCollapse.Remove

删除按钮,基于 antd Button(type="text"),默认图标为 DeleteOutlined:

属性名 类型 描述 默认值
title ReactText 文案 —
  • 点击后调用 array.field.remove(index)(array-base/index.tsx);
  • 同样支持 title 字段映射与 onClick={e => e.preventDefault()} 禁用默认行为;
  • 其余属性参考 antd Button / Icon 相关文档。

ArrayCollapse.MoveDown

下移按钮,默认图标 DownOutlined:

属性名 类型 描述 默认值
title ReactText 文案 —

点击后调用 array.field.moveDown(index);moveDown 在到达数组末尾时会回卷到第一个元素(见 ArrayField.ts)。其余属性与 title 映射、e.preventDefault() 禁用规则同上。

ArrayCollapse.MoveUp

上移按钮,默认图标 UpOutlined:

属性名 类型 描述 默认值
title ReactText 文案 —

点击后调用 array.field.moveUp(index);moveUp 在到达数组头部时会回卷到最后一个元素(见 ArrayField.ts)。其余属性同上。

ArrayCollapse.Index

索引渲染器,无属性。在面板头部渲染 #1.、#2. 形式的当前行序号(见 array-base/index.tsx)。

ArrayCollapse.useIndex

React Hook,读取当前渲染行的索引(useIndex() 返回 ItemContext 中的 index,见 array-base/index.tsx)。可用于自定义渲染逻辑中获取"当前是第几项"。

ArrayCollapse.useRecord

React Hook,读取当前渲染行的记录数据(见 array-base/index.tsx)。record 既可以是函数(延迟求值,避免额外订阅)也可以是普通对象,适合在自定义子组件中访问当前数组项的值。

七、底层原理与进阶说明

折叠状态的自动维护

ArrayCollapse 用 useState<number<a href="https://link.gitcode.com/i/d2cc2e157e9de7b387cc813f234b1282" target="_blank">]> 管理展开面板的 key 集合,并通过 useEffect 在 !field.modified 时按 defaultOpenPanelCount 重新计算([index.tsx)。新增条目时通过 insertActiveKeys 将新面板的 key 精确插入到 activeKeys 的对应位置(index.tsx),保证新增后面板依然按顺序展开。

面板头部错误徽标

面板头部会查询当前面板地址 field.address.concat(index) 下的所有校验错误(queryFeedbacks({ type: 'error', address: path + '.**' })),存在错误时用 antd Badge 显示错误数量(index.tsx)。这意味着面板折叠后用户依然能看到该面板内部的校验失败数量,非常利于长表单的错误定位。

面板内容的三种分区渲染

ArrayCollapse 内部通过 RecursionField 的 filterProperties 将 items 内的字段划分为三个区域(index.tsx):

  • 头部(header):只渲染 Index 组件;
  • 操作区(extra):只渲染 Addition / Remove / MoveUp / MoveDown 等操作组件;
  • 内容区(content):渲染除索引与操作组件外的其余字段。

这种"按组件类型分区渲染"的模式与 ArrayTable、ArrayItems 等数组组件一致,均由 ArrayBase 提供统一的上下文(ArrayBaseContext、ItemContext)与 mixin 机制支撑。

样式与依赖

ArrayCollapse 的样式入口为 style.ts,按需引入 antd 的 collapse、empty、button、badge 样式并追加少量自定义 less(style.less 中仅设置了面板项 margin-bottom: 10px)。因此使用 ArrayCollapse 前无需额外配置,正常引入 @formily/antd 即可。

适用限制

  • ArrayCollapse 仅适用于 Schema 场景(Markup Schema / JSON Schema),通过 createSchemaField 注册后使用;
  • 若字段行数少、联动少,可优先考虑更轻量的数组组件;行数多、联动密集时 ArrayCollapse 的折叠能力能显著提升长表单的可用性;
  • 相关数组组件(ArrayTable、ArrayItems、ArrayCards 等)与 ArrayCollapse 共享同一套 ArrayBase 操作原语,学习本组件后迁移到其他数组组件成本很低。

结语

ArrayCollapse 是 Formily 处理"字段多、联动多"的数组场景的主力组件。通过本文你可以掌握:Markup Schema 与 JSON Schema 两种声明方式、defaultOpenPanelCount 与 accordion 等关键 props、Addition/Remove/MoveUp/MoveDown/Index 五个内置子组件及 useIndex/useRecord 两个 Hook,以及 effects(主动/被动)与 x-reactions 两套联动方案。深入阅读 ArrayCollapse 源码、ArrayBase 实现 与 ArrayField 模型,即可在自定义业务中按需扩展出属于自己的折叠数组组件。

登录后查看全文
formily