资讯动态

Ant Design Collapse 组件完全指南:可折叠内容面板的 API、语义化定制与 Design Token 深度解析

发布时间:2026/9/7 2:41:54 来源:尧图企业网站定制
Ant Design Collapse 组件完全指南可折叠内容面板的 API、语义化定制与 Design Token 深度解析【免费下载链接】ant-designAn enterprise-class UI design language and React UI library项目地址: https://gitcode.com/GitHub_Trending/an/ant-designCollapse 是 ant-design企业级 React UI 组件库中用于分组与收纳复杂内容区域的数据展示组件用户点击面板头部即可展开或收起内容区同时支持一次只展开一栏的手风琴Accordion模式。本文以仓库中的官方英文文档 components/collapse/index.en-US.md 为主体结合 Collapse.tsx、CollapsePanel.tsx、style/index.ts 与全部官方 demo 源码系统讲解 Collapse 的适用场景、每个 API 的含义与默认值、items 声明式配置法、Semantic DOM 语义化定制以及 Design Token 主题令牌体系并附带可复制的完整代码示例。When To Use什么场景该用 Collapse官方文档给出了两条核心适用判断分组或隐藏复杂区域让页面保持整洁例如设置中心把基础设置 / 安全设置 / 通知设置收进可展开区块Accordion手风琴模式它是 Collapse 的一种特殊形态同一时刻只允许展开一个面板。换句话说Collapse 解决的是一类典型的信息分层问题——把高频可见的标题header留在页面上把低频访问的细节body收纳起来按需展开避免长页面一次性渲染过多信息。基础用法与受控/非受控状态Collapse 支持两种状态管理方式非受控通过defaultActiveKey指定初始展开面板用户交互由组件内部维护受控通过activeKeyonChange完全由业务代码控制当前展开项。下面是最基础的用法改写自 demo/basic.tsximport { Collapse } from antd; import type { CollapseProps } from antd; const text A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found as a welcome guest in many households across the world. ; const items: CollapseProps[items] [ { key: 1, label: This is panel header 1, children: p{text}/p, }, { key: 2, label: This is panel header 2, children: p{text}/p, }, { key: 3, label: This is panel header 3, children: p{text}/p, }, ]; const App: React.FC () { const onChange (key: string | string[]) { console.log(key); }; return Collapse items{items} defaultActiveKey{[1]} onChange{onChange} /; }; export default App;注意onChange的回调参数类型在 Collapse.tsx 中定义为(key: string[]) void演示代码里同时兼容了string | string[]的写法。从源码结构看多选场景下返回的是当前所有展开面板 key 组成的数组。若需完全受控把defaultActiveKey{[1]}换成activeKey{...}并在onChange里更新状态即可。展开动画由组件内部配置在 Collapse.tsx 中可以看到openMotion复用了initCollapseMotion项目自带的展开折叠运动曲线并关闭了出现动画motionAppear: false展开完成后残留类名被置为${prefixCls}-panel-hidden以彻底隐藏内容。Accordion 手风琴一次只展开一栏手风琴模式只需加一个accordion布尔属性见 demo/accordion.tsximport { Collapse } from antd; import type { CollapseProps } from antd; // items 定义同上key 为 1 / 2 / 3 的三个面板 const App: React.FC () Collapse accordion items{items} /; export default App;手风琴模式下activeKey/defaultActiveKey通常传单个字符串或数字例如defaultActiveKey1。官方 API 表对activeKey的描述是默认为空、在 accordion 模式中默认展开第一个面板的 key。API 全解析Collapse 组件属性官方文档给出如下属性表其中Global Config列表示该属性是否可被 ConfigProvider 的 componentConfig 全局统一下发PropertyDescriptionTypeDefaultVersionGlobal ConfigaccordionIf true, Collapse renders as Accordionbooleanfalse×activeKeyKey of the active panelstring[] | string / number[] | numberNo default value. In accordion mode, its the key of the first panel×borderedToggles rendering of the border around the collapse blockbooleantrue×classNamesCustomize class for each semantic structure inside the component. Supports object or function.RecordSemanticDOM, string|(info: { props }) RecordSemanticDOM, string-6.0.0支持collapsibleSpecify how to trigger Collapse. Either by clicking icon or by clicking any area in header or disable collapse functionality itselfheader|icon|disabled-4.9.0×defaultActiveKeyKey of the initial active panelstring[] | string / number[] | number-×destroyInactivePanelDestroy Inactive Panel (已废弃)booleanfalse×destroyOnHiddenDestroy Inactive Panel卸载隐藏面板内容booleanfalse5.25.0×expandIconCustomize the collapse expand icon(panelProps) ReactNode-5.15.0支持全局expandIconPlacementSet expand icon placementstart|endstart×expandIconPositionSet expand icon position请改用expandIconPlacementstart|end-4.21.0×ghostMake the collapse borderless and its background transparentbooleanfalse4.4.0×sizeSet the size of collapselarge|medium|smallmedium5.2.0×stylesCustomize inline style for each semantic structure. Supports object or function.RecordSemanticDOM, CSSProperties|(info: { props }) RecordSemanticDOM, CSSProperties-6.0.0支持全局onChangeCallback function executed when active panel is changedfunction-×itemscollapse items contentItemType-5.6.0×源码级核对与关键属性的补充解读对照 Collapse.tsx 的实现可以确认以下几点bordered / ghost 类名机制bordered{false}会附加${prefixCls}-borderless类ghost会附加${prefixCls}-ghost类视觉差异完全由 style/index.ts 中的genBorderlessStyle与genGhostStyle驱动。ghost 模式下面板无边框、背景透明适合浅色页面顶部等需要弱化容器视觉的场景。size 的默认值与继承链size的类型源自 ConfigProvider 的SizeType组件通过useSize合并「自身 prop → ConfigProvider 全局 size → 默认 middle」三层取值Collapse.tsx。因此文档表格中的默认值medium与代码中的回退值middle语义一致仅在无任何全局配置时生效。expandIconPosition 已废弃代码中使用mergedPlacement expandIconPlacement ?? expandIconPosition ?? start做向后兼容同时在非生产环境下通过devUseWarning打出 deprecated 警告Collapse.tsx提示改用expandIconPlacement。destroyInactivePanel 已废弃同理被destroyOnHidden取代兼容逻辑为destroyOnHidden ?? destroyInactivePanelCollapse.tsx。语义上destroyOnHidden强调面板被隐藏时销毁其 DOM 子树适合内容重、需要释放内存或重置内部状态的场景代价是每次展开都会重新渲染内容节点与forceRender配合时需按需选择。RTL 支持当 ConfigProvider 的directionrtl时根节点会加上${prefixCls}-rtl类Collapse.tsx展开箭头旋转方向也随之翻转style/index.ts。展开/收起箭头动画箭头使用RightOutlined图标展开时旋转 90°RTL 下为 -90°旋转过渡时长取自motionDurationSlow。若箭头本身可作为点击热区collapsibleicon或header会为图标附加aria-labelexpanded/collapsed否则标为aria-hidden保证可访问性Collapse.tsx。三种尺寸size仓库 demo/size.tsx 展示了small/medium缺省/large三种尺寸分别通过${prefixCls}-small与${prefixCls}-large类切换内边距与字号。从样式源码style/index.ts可以看到三种尺寸影响 header 与 body 的padding以及大号尺寸的fontSize取fontSizeLG。面板折叠触发区域collapsiblecollapsible决定点哪里才能折叠取值header、icon、disabled见 demo/collapsible.tsxCollapse collapsibleheader defaultActiveKey{[1]} items{items} / Collapse collapsibleicon defaultActiveKey{[1]} items{items} / Collapse collapsibledisabled items{items} /header点击标题文字或图标都可折叠/展开icon只有点击箭头图标时才可折叠适合标题本身还承载其他交互比如标题内含链接或复选框的场景disabled完全禁用折叠交互头部呈现禁用色与not-allowed光标。对应样式位于 style/index.ts其中-collapsible-header/-collapsible-icon分别把cursor: pointer限制在标题或图标局部。从 v4.9.0 起该属性也可配置在单个面板上见下文 ItemType 与 Collapse.Panel。面板级disabled写法已废弃源码会在非生产环境提示改用collapsibledisabledCollapsePanel.tsx。ItemType推荐的面板声明式配置v5.6.0自 5.6.0 起官方推荐用items数组声明面板内容。ItemType 属性表如下PropertyDescriptionTypeDefaultVersionclassNamesSemantic structure classNameRecordheader \| body, string-5.21.0collapsibleSpecify whether the panel be collapsible or the trigger areaheader|icon|disabled-childrenBody area contentReactNode-extraThe extra element in the cornerReactNode-forceRenderForced render of content on panel, instead of lazy rendering after clicking on headerbooleanfalsekeyUnique key identifying the panel from among its siblingsstring | number-labelTitle of the panelReactNode--showArrowIf false, panel will not show arrow icon. 若为 false则 collapsible 不能设为iconbooleantruestylesSemantic DOM styleRecordheader \| body, CSSProperties-5.21.0extra面板右上角的附加节点extra用于在面板角落追加操作节点如编辑按钮、状态标签等见 demo/extra.tsx。嵌套面板、图标与隐藏箭头仓库 demo 还覆盖了这些 ItemType/外观组合嵌套面板Nested panel见 demo/mix.tsx一个面板的children里再放一层 Collapse实现两级收纳。自定义展开图标expandIcon见 demo/icon.tsx可通过expandIcon{(panelProps) ...}完全替换箭头图标面板标题中也支持混排图标。图标由.anticon包裹或裸svg渲染时style/index.ts 对裸svg额外做了inline-blockvertical-align: middle处理确保任何来源的图标都与标题文字垂直居中——这对 Tailwind Preflight 等强制svg { display: block }的 CSS Reset 环境尤为重要。无箭头面板见 demo/noarrow.tsxshowArrow{false}时不再渲染箭头图标。注意 ItemType 表的约束如果showArrow{false}面板的collapsible不能再设成icon否则点击区域不存在。CollapsePanel源码中showArrow默认值为true隐藏箭头时会追加${prefixCls}-no-arrow类CollapsePanel.tsx。更多面板外观组合Borderless无边框demo/borderless.tsx 展示bordered{false}容器不再有外边框、内容区背景透明仅保留面板间的分隔线。Ghost Collapse幽灵面板demo/ghost.tsx 展示ghost在无边框基础上进一步去掉面板间分隔线并让背景完全透明适合嵌在卡片或其他容器内部。自定义面板Custom Paneldemo/custom.tsx 演示了items各字段的组合玩法label、extra、自定义展开图标等。Collapse.Panel已废弃的写法5.6.0 之前使用Collapse.Panel作为子组件逐面板配置。官方文档明确标记为Deprecated使用 v5.6.0 时优先使用items配置。其完整属性表为PropertyDescriptionTypeDefaultVersioncollapsibleSpecify whether the panel be collapsible or the trigger areaheader|icon|disabled-4.9.0icon: 4.24.0extraThe extra element in the cornerReactNode-forceRenderForced render of content on panel, instead of lazy rendering after clicking on headerbooleanfalseheaderTitle of the panelReactNode-keyUnique key identifying the panel from among its siblingsstring | number-showArrowIf false, panel will not show arrow icon. 若为 false则 collapsible 不能设为iconbooleantrue传统写法大致如下Collapse defaultActiveKey{[1]} Collapse.Panel headerThis is panel header 1 key1 p{text}/p /Collapse.Panel Collapse.Panel headerThis is panel header 2 key2 p{text}/p /Collapse.Panel /Collapse从实现看Collapse.Panel是对底层RcCollapse.Panel的极薄封装CollapsePanel.tsx仅负责统一prefixCls、处理showArrow类名与disabled废弃告警而Collapse组件本身通过Object.assign(Collapse, { Panel: CollapsePanel })挂载子组件Collapse.tsx。官方之所以废弃Collapse.Panel是因为父组件 APIactiveKey、accordion、collapsible 等更便于通过items数据结构化传递与类型推导CollapseProps[items]提供完整的 TypeScript 提示。Semantic DOM语义化结构与 classNames / styles 定制6.0.0 起 Collapse 支持按语义节点做样式定制。Semantic DOM 定义在 demo/_semantic.tsx共包含五个可定制节点语义节点说明classNames/styles 支持版本root根元素控制容器整体布局与外观边框、圆角、背景6.0.0header面板头部flex 布局、内边距、颜色、行高、光标、过渡动画等交互样式5.21.0title标题文字flex 自适应布局与排版6.0.0body内容区内边距、颜色、背景等展示样式5.21.0icon展开/收起箭头字号、过渡动画、旋转变换6.0.0对应的类型定义见 Collapse.tsxclassNames/styles均可传静态对象或函数函数接收{ props }可按props.size、props.accordion等动态返回。注意函数形态只在 6.0.0 才支持相关类型由useMergeSemantic/GenerateSemantic推导Collapse.tsx。下面是参照 demo/style-class.tsx 的用法Custom semantic dom styling6.0.0 新增import { Collapse, Flex } from antd; import type { CollapseProps, GetProp } from antd; import { createStaticStyles } from antd-style; // 1) 对象写法直接给各语义节点覆盖 style const styles: CollapseProps[styles] { root: { backgroundColor: #fafafa, border: 1px solid #e0e0e0, borderRadius: 8 }, header: { backgroundColor: #f0f0f0, padding: 12px 16px, color: #141414 }, }; // 2) 函数写法根据 props 动态返回 style const stylesFn: CollapseProps[styles] ({ props }): GetPropCollapseProps, styles, Return { if (props.size large) { return { root: { backgroundColor: #fff, border: 1px solid #696FC7, borderRadius: 8 }, header: { backgroundColor: #F5EFFF, padding: 12px 16px, color: #141414 }, }; } }; const App: React.FC () { const sharedProps: CollapseProps { classNames: createStaticStyles(({ css }) ({ root: cssbackground-color: #fafafa; border: 1px solid #e0e0e0; border-radius: 8px;, })), items: [{ key: 1, label: This is panel header 1, children: p.../p }], }; return ( Flex vertical gapmedium Collapse {...sharedProps} defaultActiveKey{[1]} styles{styles} / Collapse {...sharedProps} defaultActiveKey{[2]} styles{stylesFn} sizelarge / /Flex ); };同时ItemType 层面还支持header/body两个更细粒度的语义槽classNames/styles5.21.0 起实现同一个 Collapse 里不同面板样式不同的效果。需要说明的是此能力是 cssinjs 体系下官方推荐的精准定制手段相比依赖深层 DOM 选择器覆盖语义化 API 的类名在 hash 化后依然稳定、不受内部 DOM 结构调整影响。仓库中配套的测试文件 demo-semantic.test.tsx 与 semantic.test.tsx 会对这些结构做渲染级验证。Design Token组件级主题令牌Collapse 的全部组件令牌定义在 style/index.ts 的ComponentToken接口并通过prepareComponentTokenstyle/index.ts给出由全局 alias token 推导的默认值。官方文档的 Design Token 表格由ComponentTokenTable componentCollapse动态渲染即来自该接口。可用令牌一览Token语义默认值来源由 alias token 推导headerPadding面板头部内边距paddingSM padding默认主题下约为12px 16pxheaderPaddingSM小尺寸面板头部内边距paddingXS paddingSM paddingXS paddingXSheaderPaddingLG大尺寸面板头部内边距padding paddingLG padding paddingheaderBg面板头部背景色colorFillAltercontentPadding面板内容区内边距padding 1616 为固定值contentPaddingSM小尺寸内容区内边距paddingSMcontentPaddingLG大尺寸内容区内边距paddingLGcontentBg面板内容区背景色colorBgContainerborderlessContentPadding无边框borderless/ghost内容区内边距paddingXXS 16 paddingborderlessContentBg无边框内容区背景色transparent源码中headerPadding等头部内边距会区分大中小三档大号走headerPaddingLG与contentPaddingLG小号走headerPaddingSM与contentPaddingSM默认走基础令牌并在genBaseStyle中通过 -small/-large选择器落地style/index.ts。此外代码内部还合并了一个非导出的派生令牌collapsePanelBorderRadius其值取borderRadiusLG用于根容器与首/末面板头的圆角衔接保证圆角视觉统一style/index.ts。覆盖方式有两种// 1) ConfigProvider 全局覆盖 import { ConfigProvider } from antd; ConfigProvider theme{{ components: { Collapse: { headerBg: #f5f5f5, contentPadding: 20px 24px, headerPadding: 12px 20px, }, }, }} App / /ConfigProvider; // 2) 主题算法 token 级别覆盖与语义化styles相比Design Token 更适合团队级的全局主题统一暗色模式、品牌色换肤其改动会平滑传递到所有 Collapse 实例。在 ConfigProvider 中全局统一配置结合 API 表中 Global Config 一列部分能力为 ×即不可全局化与 Collapse.tsx 的实现可以看到Collapse 已接入useComponentConfig(collapse)支持以下能力在 ConfigProvider 层全局下发className/style/classNames/styles、expandIcon5.15.0 起。可用的全局覆盖属性从CollapseSemanticTypeCollapse.tsx与contextExpandIcon的读取逻辑Collapse.tsx可见一斑ConfigProvider componentConfig{{ Collapse: { styles: { header: { fontWeight: 600 } }, expandIcon: (props) span{props.isActive ? − : }/span, }, }} 而accordion、collapsible、bordered、ghost、size、activeKey等行为性/状态性属性属于组件实例语义官方 API 表标记为 ×不能全局下发——这与 ant-design 对 componentConfig 的通用设计一致通用组件 props 的全局配置说明可参阅 docs/react/common-props 相关文档本仓库对应说明位于 docs/react 目录。可访问性与测试保障Collapse 在仓库中配有完整测试行为测试 index.test.tsx、无障碍专项测试 accessibility.test.tsx 与 a11y.test.ts、demo 回归测试 demo.test.ts 及图片回归 image.test.ts。无障碍实现要点可从 Collapse.tsx 源码核对展开箭头在可交互时携带aria-labelexpanded/collapsed不可交互时标为aria-hidden面板头部是可聚焦元素genFocusStyle支持键盘操作展开/收起折叠中的面板通过leavedClassName-panel-hidden从可访问树中移除。小结本文围绕官方文档完整走了一遍 ant-design Collapse 的使用全貌基础/受控用法与手风琴模式、12 项组件属性的默认值与行为含bordered、ghost、size、collapsible、expandIconPlacement、destroyOnHidden等、5.6.0 推荐的items声明式面板配置、已废弃的Collapse.Panel写法、Semantic DOM 五个语义节点的 classNames/styles 定制、以及 10 个组件级 Design Token 的主题化能力。所有结论均可在 components/collapse 目录下找到对应的源码、样式与测试佐证官方每个示例的独立 TSX/MD 演示也都可以直接运行参考便于你在真实项目中按需组合使用。【免费下载链接】ant-designAn enterprise-class UI design language and React UI library项目地址: https://gitcode.com/GitHub_Trending/an/ant-design创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价