You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用AntD实现横向展开的Collapse组件,替代默认垂直展开效果

AntD 官方 Collapse 组件默认仅支持垂直折叠效果,但可以通过覆盖默认样式、调整动画规则的方式,将其改造为横向折叠效果,无需额外引入其他组件。


实现方案

方法1:自定义改造AntD Collapse实现横向折叠

核心思路是覆盖Collapse默认的垂直布局逻辑,将原本的高度过渡动画替换为宽度过渡动画,具体实现代码如下:

  1. 组件逻辑代码
import { Collapse, useState } from 'antd';

const HorizontalCollapse = () => {
  const [activeKey, setActiveKey] = useState([]);

  const onChange = (key) => {
    setActiveKey(key);
  };

  return (
    <div className="horizontal-collapse-wrapper">
      <Collapse
        activeKey={activeKey}
        onChange={onChange}
        bordered={false}
        className="horizontal-collapse"
      >
        <Collapse.Panel header="面板1" key="1" className="horizontal-collapse-panel">
          <div className="panel-content">
            这是面板1的内容,横向展开展示
          </div>
        </Collapse.Panel>
        <Collapse.Panel header="面板2" key="2" className="horizontal-collapse-panel">
          <div className="panel-content">
            这是面板2的内容,横向展开展示
          </div>
        </Collapse.Panel>
      </Collapse>
    </div>
  );
};

export default HorizontalCollapse;
  1. 样式代码(以Less为例)
.horizontal-collapse-wrapper {
  height: 300px; /* 可根据业务需求自定义容器高度 */
  width: 100%;
  display: flex;
}

.horizontal-collapse {
  display: flex;
  width: 100%;
  height: 100%;
  border: none;
  background: transparent;

  /* 覆盖默认的面板垂直布局 */
  .ant-collapse-item {
    height: 100%;
    display: flex;
    flex-direction: row;
    border-bottom: none;
    border-right: 1px solid #d9d9d9; /* 将默认底部边框调整为右侧边框 */

    .ant-collapse-header {
      width: 44px; /* 折叠状态下仅展示header的宽度,可自行调整 */
      height: 100%;
      padding: 12px 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      writing-mode: vertical-lr; /* 实现文字竖排,不需要可删除该属性自行调整布局 */
    }

    .ant-collapse-content {
      height: 100%;
      overflow: hidden;
      /* 替换默认的高度过渡为宽度过渡 */
      transition: all 0.3s ease;
      max-height: 100% !important; /* 覆盖默认的max-height动画规则 */
      border-top: none;

      &.ant-collapse-content-active {
        width: 300px; /* 展开后的内容宽度,可自行调整 */
      }

      &:not(.ant-collapse-content-active) {
        width: 0;
        padding: 0;
        border: none;
      }

      .ant-collapse-content-box {
        height: 100%;
        padding: 16px;
        width: 300px; /* 和上方展开宽度保持一致即可 */
      }
    }
  }
}

注意:如果需要调整展开箭头方向,可覆盖.ant-collapse-arrow的transform属性旋转适配横向布局即可。

方法2:轻量自定义实现

如果改造Collapse默认样式的成本较高,也可以直接基于AntD的基础组件(比如Button、Card)手写横向折叠逻辑,只需控制内容区域的width属性配合transition动画即可,灵活度更高。


内容的提问来源于stack exchange,提问作者Step

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 13:06:08