react-collapse: 折叠组件

一个常用的 collapse 组件,有不同的实现方式,选择了一个相对优雅的方式实现
更新于: 2024-05-11 01:25:10
项目主页: https://github.com/afeiship/react-collapse

安装

npm install -S @jswork/react-collapse

使用

@import "~@jswork/react-collapse/dist/style.css";

// or use sass
@import "~@jswork/react-collapse/dist/style.scss";
import ReactCollapse from '@jswork/react-collapse';
import './index.css';
import '@jswork/react-collapse/dist/style.scss';

function App() {
  return (
    <div className="m-10 p-4 shadow bg-gray-100 text-gray-800 hover:shadow-md transition-all">
      <div className="badge badge-warning absolute right-0 top-0 m-4">
        Build Time: {BUILD_TIME}
      </div>
      <h1>react-collapse</h1>
      <div className="y-3">
        <ReactCollapse
          collapsed
          onChange={e => console.log(e)}
          summary={
            <header className="cursor-pointer bg-gray-200 px-4 py-1">Header(slow element has bug)</header>
          }>
          <div className="p-5 rounded-md rounded-t-none bg-green-100">
            {/*<img width={500} height={200} src="https://via.placeholder.com/500x200" alt="placeholder" />*/}
            <img src="https://via.placeholder.com/500x200" alt="placeholder" />
          </div>
        </ReactCollapse>
      </div>
    </div>
  );
}

export default App;

方案

  • 方案1: max-height: 9999px
  • 方案2: 动态计算 max-height
  • 方案3: 使用 fadeIn 效果
  • 方案4: grid 的方案(不考虑兼容的情况下,完美)
  • 方案5: 其它 scale 方案

各方案对比

名称优点缺点
方案一: max-height: 9999px无需JS,基本就可以实现缺点,动画在打开/关闭的时候,会有 卡顿 体验不好
方案2: 动态计算 max-height

与方案1,本质是同一方案,这里会做一个简单的计算

  • 图片预加载(max-height: 0 的时候,不加载)
 
方案3: 使用 fadeIn 效果这个就使用 opacity 利用 element-visible 方式可以实现没有明显缺点,只不过,有时候需要使用 slideUp/Down 的显示效果

参考

https://github.com/nkbt/react-collapse/issues/206

https://dev.to/alexandprivate/the-ultimate-collapsible-component-with-height-auto-detection-25pi

https://github.com/Stanko/react-animate-height

https://dev.to/francescovetere/css-trick-transition-from-height-0-to-auto-21de