Formily 折叠面板 FormCollapse 完全指南:Schema 场景下的空间管理利器

原创2026-09-22 18:58:281,339 阅读
文章标签:前端UI组件

Formily 折叠面板 FormCollapse 完全指南:Schema 场景下的空间管理利器

折叠面板(FormCollapse)是 Formily 体系中用于“布局空间要求较高”的表单场景的经典组件:它能把一组字段收纳进可展开/收起的面板,让长表单变得紧凑、层次分明。本文以 @formily/next 的 FormCollapse 官方文档 为骨架,结合 form-collapse 源码 深入讲解其 Markup Schema / JSON Schema 两种用法、createFormCollapse 响应式模型 API,以及底层实现原理,读完即可在项目中落地可折叠表单并在代码层面真正理解它的工作机制。

使用前提:FormCollapse 只能在 Schema 场景中使用(无论是 Markup Schema 还是 JSON Schema),因为它依赖 x-component、x-decorator 等 Schema 描述来收集面板结构与字段布局。

一、FormCollapse 的核心概念

FormCollapse 的本质是对底层 UI 组件库 Collapse(折叠面板)的 Formily 化封装:

  • 在 @formily/next 中,它基于 @alifd/next 的 Collapse 与 Badge 构建(见 style.ts 中导入的 collapse/style 与 badge/style);
  • 在 @formily/antd 中,它基于 antd 的 Collapse 与 Badge 构建(见 antd 版实现)。

它由两个关键角色组成:

  1. FormCollapse:容器组件,负责接收 Schema、收集面板、渲染底层 Collapse,并通过 formCollapse 模型驱动展开状态;
  2. FormCollapse.CollapsePanel:面板标记组件,本身不做渲染(直接返回 Fragment),只用于在 Schema 中声明“这里是面板边界”:
const CollapsePanel: React.FC<React.PropsWithChildren<CollapsePanelProps>> = ({
  children,
}) => {
  return <Fragment>{children}</Fragment>
}

也就是说,面板的真正渲染逻辑完全由外层 FormCollapse 通过扫描子 Schema 完成,CollapsePanel 只是一个 Schema 占位符。

二、Markup Schema 案例:从零搭建三面板折叠表单

Markup Schema(标记式)允许直接用 JSX 描述 Schema,是最直观的写法。以下案例完整继承自官方文档,构建了 panel1/panel2/panel3 三个折叠面板,每个面板内各有一个必填输入框:

import React from 'react'
import {
  FormCollapse,
  FormItem,
  Input,
  FormButtonGroup,
  Submit,
  FormLayout,
} from '@formily/next'
import { createForm } from '@formily/core'
import { FormProvider, createSchemaField } from '@formily/react'
import { Button } from '@alifd/next'

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

const form = createForm()
const formCollapse = FormCollapse.createFormCollapse()

export default () => {
  return (
    <FormProvider form={form}>
      <FormLayout labelCol={6} wrapperCol={10}>
        <SchemaField>
          <SchemaField.Void
            title="Folding Panel"
            x-decorator="FormItem"
            x-component="FormCollapse"
            x-component-props={{
              formCollapse,
            }}
          >
            <SchemaField.Void
              name="panel1"
              x-component="FormCollapse.CollapsePanel"
              x-component-props={{ title: 'A1' }}
            >
              <SchemaField.String
                name="aaa"
                title="AAA"
                x-decorator="FormItem"
                required
                x-component="Input"
              />
            </SchemaField.Void>
            <SchemaField.Void
              name="panel2"
              x-component="FormCollapse.CollapsePanel"
              x-component-props={{ title: 'A2' }}
            >
              <SchemaField.String
                name="bbb"
                title="BBB"
                x-decorator="FormItem"
                required
                x-component="Input"
              />
            </SchemaField.Void>
            <SchemaField.Void
              name="panel3"
              x-component="FormCollapse.CollapsePanel"
              x-component-props={{ title: 'A3' }}
            >
              <SchemaField.String
                name="ccc"
                title="CCC"
                x-decorator="FormItem"
                required
                x-component="Input"
              />
            </SchemaField.Void>
          </SchemaField.Void>
        </SchemaField>
        <FormButtonGroup.FormItem>
          <Button
            onClick={() => {
              form.query('panel3').take((field) => {
                field.visible = !field.visible
              })
            }}
          >
            Show/hide the last tab
          </Button>
          <Button
            onClick={() => {
              formCollapse.toggleActiveKey('panel2')
            }}
          >
            Switch to the second Tab
          </Button>
          <Submit onSubmit={console.log}>Submit</Submit>
        </FormButtonGroup.FormItem>
      </FormLayout>
    </FormProvider>
  )
}

这个案例值得注意的三个设计点:

  1. 容器字段必须是 SchemaField.Void:折叠面板本身不产生数据值,属于纯布局节点,因此 x-component="FormCollapse" 的字段必须声明为 type: 'void' 类型(在 Markup 中用 SchemaField.Void)。
  2. 面板节点也是 Void,且以 name 作为唯一标识:panel1/panel2/panel3 这些 name 就是后面 API 操作里的 “ActiveKey”。
  3. 通过 x-component-props 传入 formCollapse 模型:展开状态由模型驱动,面板与表单字段的值状态(如校验错误徽标)完全解耦。

操作按钮的两种典型交互

示例中的两个按钮展示了折叠面板最常见的两种外部控制方式:

  • 显隐控制:form.query('panel3').take(field => field.visible = !field.visible) 利用 Formily 字段查询 API 直接翻转面板字段的 visible,配合下方源码中的 usePanels 逻辑,被隐藏的面板会自动从渲染列表中剔除;
  • 展开切换:formCollapse.toggleActiveKey('panel2') 调用模型的切换方法,等价于“若已展开则收起,否则展开”。

三、JSON Schema 案例:面向动态渲染的纯数据写法

当 Schema 来自服务端或需要序列化传输时,应使用 JSON Schema 写法。它与 Markup 版等价,核心差异是:formCollapse 模型不再直接作为对象属性传入,而是通过 '{{formCollapse}}' 表达式与 scope 注入:

import React from 'react'
import {
  FormCollapse,
  FormItem,
  Input,
  FormButtonGroup,
  Submit,
  FormLayout,
} from '@formily/next'
import { createForm } from '@formily/core'
import { FormProvider, createSchemaField } from '@formily/react'
import { Button } from '@alifd/next'

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

const form = createForm()
const formCollapse = FormCollapse.createFormCollapse()

const schema = {
  type: 'object',
  properties: {
    collapse: {
      type: 'void',
      title: 'Folding Panel',
      'x-decorator': 'FormItem',
      'x-component': 'FormCollapse',
      'x-component-props': {
        formCollapse: '{{formCollapse}}',
      },
      properties: {
        panel1: {
          type: 'void',
          'x-component': 'FormCollapse.CollapsePanel',
          'x-component-props': {
            title: 'A1',
          },
          properties: {
            aaa: {
              type: 'string',
              title: 'AAA',
              'x-decorator': 'FormItem',
              required: true,
              'x-component': 'Input',
            },
          },
        },
        panel2: {
          type: 'void',
          'x-component': 'FormCollapse.CollapsePanel',
          'x-component-props': {
            title: 'A2',
          },
          properties: {
            bbb: {
              type: 'string',
              title: 'BBB',
              'x-decorator': 'FormItem',
              required: true,
              'x-component': 'Input',
            },
          },
        },
        panel3: {
          type: 'void',
          'x-component': 'FormCollapse.CollapsePanel',
          'x-component-props': {
            title: 'A3',
          },
          properties: {
            ccc: {
              type: 'string',
              title: 'CCC',
              'x-decorator': 'FormItem',
              required: true,
              'x-component': 'Input',
            },
          },
        },
      },
    },
  },
}

export default () => {
  return (
    <FormProvider form={form}>
      <FormLayout labelCol={6} wrapperCol={10}>
        <SchemaField schema={schema} scope={{ formCollapse }} />
        <FormButtonGroup.FormItem>
          <Button
            onClick={() => {
              form.query('panel3').take((field) => {
                field.visible = !field.visible
              })
            }}
          >
            Show/hide the last tab
          </Button>
          <Button
            onClick={() => {
              formCollapse.toggleActiveKey('panel2')
            }}
          >
            Switch to the second Tab
          </Button>
          <Submit onSubmit={console.log}>Submit</Submit>
        </FormButtonGroup.FormItem>
      </FormLayout>
    </FormProvider>
  )
}

两种写法的对应关系总结如下:

维度 Markup Schema JSON Schema
模型注入 x-component-props={{ formCollapse }} 'x-component-props': { formCollapse: '{{formCollapse}}' } + scope={{ formCollapse }}
字段类型 SchemaField.Void type: 'void'
必填声明 required required: true
渲染入口 <SchemaField> 子节点 <SchemaField schema={schema} scope={...} />

四、API 详解

4.1 FormCollapse 容器组件

属性名 类型 描述 默认值
formCollapse IFormCollapse 传入通过 createFormCollapse 创建出来的模型 无

容器组件其余属性直接透传给 @alifd/next 的 Collapse(如 accordion、expandedKeys 等),可参考 alifd/next 的 Collapse 文档(antd 版本则参考 antd Collapse)。

从 源码实现 看,FormCollapse 是一个由 observer 包裹的响应式组件,其内部逻辑可拆解为:

  1. 面板收集(usePanels):通过 useFieldSchema().mapProperties 遍历子 Schema,命中 x-component 包含 CollapsePanel 的节点即视为面板,并拼接面板 props——title 优先取 x-component-props.title,否则回退到 Schema 的 title;同时过滤掉 display 为 none 或 hidden 的字段,这是“显示/隐藏最后一个面板”按钮能生效的底层原因:
const panels: { name: SchemaKey; props: any; schema: Schema }[] = []
schema.mapProperties((schema, name) => {
  const field = collapseField.query(collapseField.address.concat(name)).take()
  if (field?.display === 'none' || field?.display === 'hidden') return
  if (schema['x-component']?.indexOf('CollapsePanel') > -1) {
    panels.push({
      name,
      props: {
        ...schema?.['x-component-props'],
        title: schema?.['x-component-props']?.title || schema?.title,
        key: schema?.['x-component-props']?.key || name,
      },
      schema,
    })
  }
})
  1. 展开键计算(takeExpandedKeys):展开状态的优先级为——显式传入的 props.expandedKeys > formCollapse.activeKeys > 手风琴模式下取第一个面板 panels[0]?.name > 默认展开全部面板:
const takeExpandedKeys = () => {
  if (props.expandedKeys) return props.expandedKeys
  if (_formCollapse?.activeKeys) return _formCollapse?.activeKeys
  if (props.accordion) return panels[0]?.name
  return panels.map((item) => item.name)
}
  1. 错误徽标(badgedHeader):通过 field.form.queryFeedbacks({ type: 'error', address: ... }) 查询面板内所有字段的校验错误,若有错误则在面板标题上显示 Badge 徽标,实现“哪个面板有错一眼可见”的体验(这依赖 style.ts 中引入的 badge 样式)。

  2. 状态同步:用户点击展开/收起时,底层 Collapse 触发 onExpand,组件将其同步回模型 _formCollapse?.setActiveKeys?.(keys),保证 UI 与模型单向流动。

4.2 FormCollapse.CollapsePanel

面板占位组件,接受 title 等面板 props(透传给底层 Collapse.Panel),配合 RecursionField 递归渲染面板内字段:

<Collapse.Panel key={index} {...props} title={badgedHeader(name, props)}>
  <RecursionField schema={schema} name={name} />
</Collapse.Panel>

官方文档中该组件的其余属性同样参考底层 Collapse 的面板 API(如 title、key 等)。

4.3 FormCollapse.createFormCollapse

静态工厂方法,创建一个基于 @formily/reactive 的 model() 响应式模型(创建后通过 markRaw 标记,避免被表单观察系统过度代理),用于驱动面板展开状态。其完整类型签名与接口如下:

type ActiveKey = string | number
type ActiveKeys = string | number | Array<string | number>

interface createFormCollapse {
  (defaultActiveKeys?: ActiveKeys): IFormCollapse
}

interface IFormCollapse {
  //激活主键列表
  activeKeys: ActiveKeys
  //是否存在该激活主键
  hasActiveKey(key: ActiveKey): boolean
  //设置激活主键列表
  setActiveKeys(keys: ActiveKeys): void
  //添加激活主键
  addActiveKey(key: ActiveKey): void
  //删除激活主键
  removeActiveKey(key: ActiveKey): void
  //开关切换激活主键
  toggleActiveKey(key: ActiveKey): void
}

各方法的实现细节(见 next 版源码):

方法 行为说明
hasActiveKey(key) activeKeys 为数组时用 includes 判断;为单值时用 == 宽松比较(兼容 string/number)
setActiveKeys(keys) 整体覆盖 activeKeys,底层 Collapse 的 onExpand 回调会调用它
addActiveKey(key) 已存在则直接返回,否则用 toArr(activeKeys).concat(key) 追加
removeActiveKey(key) 数组模式时过滤掉该键;单值模式时置空(next 版置为 [],antd 版置为 '')
toggleActiveKey(key) 存在则移除,不存在则添加——即文档案例中“Switch to the second Tab”按钮的行为

默认展开参数的用法:createFormCollapse() 不传参时所有面板默认展开;传入如 createFormCollapse(['panel1']) 可指定初始展开的面板;结合底层 accordion 属性还能实现手风琴效果(同时只展开一个面板)。

五、从源码看 FormCollapse 的实现原理

把 form-collapse/index.tsx 完整读一遍,可以得到几条对使用非常有价值的实现事实:

  1. 面板收集依赖 Schema 而非真实 DOM:FormCollapse 不直接读取 children,而是通过 useFieldSchema() 拿到当前字段的 Schema,再 mapProperties 扫描。这意味着“面板里有什么”完全由 Schema 结构决定,也解释了为什么 FormCollapse 只能用于 Schema 场景。
  2. 面板渲染通过 RecursionField 递归完成:每个面板内包裹 RecursionField schema={schema} name={name},字段的 x-decorator(FormItem)与 x-component(Input)会在递归中自动解析,因此示例中面板里的输入框无需任何额外注册。
  3. 展开状态与表单值状态完全分离:activeKeys 存在 formCollapse 模型中,而字段值/校验状态存在 form 中;组件只是二者的“桥”,通过 observer 订阅模型变化触发重渲染。
  4. 跨 UI 库的一致性:antd 版实现 与 next 版结构几乎一致,差异仅在底层组件 API 名称(antd 用 header/activeKey/defaultActiveKey 与 onChange,next 用 title/expandedKeys/defaultExpandedKeys 与 onExpand),以及 antd 版面板加了 forceRender 保证隐藏面板内容也能被表单收集。因此本文的 Schema 写法、模型 API 在 @formily/antd 下同样成立,只需替换 title 为 header。
  5. 样式按需引入:组件通过 style.ts 显式引入 @alifd/next 的 collapse 与 badge 样式,在 @formily/next 的按需加载体系中无需额外配置。

六、适用场景与使用建议

FormCollapse 适合以下典型场景:

  • 高密度长表单:如多分组信息录入,用折叠面板把无关分组收起,降低页面滚动成本;
  • 步骤无关的分区表单:面板间没有强先后依赖,只做空间组织;
  • 服务端下发的动态表单:JSON Schema 写法可以原样序列化,配合 scope 注入模型即可驱动展开状态;
  • 需要错误感知的分区表单:面板标题自动显示错误徽标,便于快速定位校验失败分区。

需要留意的是:FormCollapse 只是“折叠展示”层,不参与数据收集(面板是 void 字段),所有字段值仍通过 Formily 的 form 统一管理,Submit 提交的也是完整表单值——折叠与否不影响数据结构和提交逻辑。

至此,从 Markup Schema 到 JSON Schema,从组件 API 到响应式模型源码,FormCollapse 的完整使用链路已经打通。实际项目中建议优先用 createFormCollapse 统一管理展开状态(而非直接操作底层 Collapse props),这样既能享受响应式状态同步,也能在任意位置通过 toggleActiveKey 等 API 精细控制面板行为。

登录后查看全文
formily