react 实现收缩栏
实现收缩栏的基本思路
在React中实现收缩栏(Collapsible Panel)通常涉及状态管理、动画效果和用户交互。以下是几种常见方法:
使用React状态管理
通过useState控制收缩栏的展开/折叠状态:
import React, { useState } from 'react';
function CollapsiblePanel() {
const [isExpanded, setIsExpanded] = useState(false);
return (
<div>
<button onClick={() => setIsExpanded(!isExpanded)}>
{isExpanded ? 'Collapse' : 'Expand'}
</button>
{isExpanded && (
<div className="content">
This is the collapsible content
</div>
)}
</div>
);
}
添加CSS过渡动画
使用CSS实现平滑的展开/折叠效果:
.content {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease-out;
}
.content.expanded {
max-height: 500px; /* 调整为实际内容高度 */
}
<div className={`content ${isExpanded ? 'expanded' : ''}`}>
This content will animate smoothly
</div>
使用第三方库
考虑使用成熟的UI库如Material-UI或Ant Design:
import { Collapse } from 'antd';
function Panel() {
return (
<Collapse>
<Collapse.Panel header="Click to expand" key="1">
Content inside the panel
</Collapse.Panel>
</Collapse>
);
}
高级实现:自定义钩子
创建可复用的useCollapse钩子:
function useCollapse(initialState = false) {
const [isExpanded, setIsExpanded] = useState(initialState);
const toggle = () => setIsExpanded(!isExpanded);
return { isExpanded, toggle };
}
function MyComponent() {
const { isExpanded, toggle } = useCollapse();
return (
<div>
<button onClick={toggle}>Toggle</button>
<div style={{ height: isExpanded ? 'auto' : 0, overflow: 'hidden' }}>
Content
</div>
</div>
);
}
性能优化建议
对于复杂内容,考虑使用React.memo避免不必要的重渲染:
const MemoizedContent = React.memo(function Content({ text }) {
return <div>{text}</div>;
});
function Panel() {
// ...使用MemoizedContent作为子组件
}
以上方法可根据具体需求组合使用,简单场景用状态管理即可,复杂需求可考虑第三方库或自定义钩子方案。






