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

如何为React中的Collapsible折叠组件添加平滑展开收起动画?

折叠组件平滑动画实现方案

1. 修正index.js逻辑

现有代码核心问题是通过isOpen直接条件卸载内容DOM节点,元素被移除无法触发过渡动画,需要保留DOM节点仅通过类名控制状态,修改后代码如下:

import { useState } from "react"; // 补充遗漏的useState导入
import { FaArrowDown } from "react-icons/fa";
import { CollapsibleContainer, ArrowContainer } from "./CollapsibleElements";

const Collapsible = (props) => {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <CollapsibleContainer>
      <div className="collapsible">
        <ArrowContainer>
          <FaArrowDown 
            onClick={() => setIsOpen(!isOpen)} 
            className={isOpen ? "arrow rotate" : "arrow"}
            style={{fontSize: '1.5rem', marginBottom: 15, transition: 'transform 0.3s ease'}} 
          />
        </ArrowContainer>
        {/* 移除条件渲染,保留DOM节点用于触发过渡 */}
        <div className={isOpen ? "content show" : "content"}>
          <p>Content inside here</p>
          {/* 支持传入自定义内容 */}
          {props.children}
        </div>
      </div>
    </CollapsibleContainer>
  );
};

export default Collapsible;

2. 新增过渡样式

普通CSS写法

在全局样式或对应CSS文件中添加以下规则即可实现平滑效果:

.content {
  max-height: 0;
  overflow: hidden;
  opacity: 0;
  padding: 0 1rem;
  transition: all 0.3s ease;
}

.content.show {
  max-height: 1000px; /* 设置为远超内容最大高度的值即可适配不同内容长度 */
  opacity: 1;
  padding: 1rem;
}

.arrow.rotate {
  transform: rotate(180deg);
}

styled-components适配写法

如果使用styled-components定义样式,直接修改CollapsibleElements.js中的组件规则即可,无需额外编写CSS类。

优化方案(可选)

如果觉得固定max-height导致动画速度和内容高度不匹配,可以用useRef获取内容真实高度动态设置:

const contentRef = useRef(null);
// 展开时设置max-height为contentRef.current.scrollHeight即可实现精准匹配的动画速度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:15:00