react实现展开收起功能
实现展开收起功能的方法
在React中实现展开收起功能可以通过状态管理和条件渲染来完成。以下是几种常见的实现方式:
使用useState钩子管理状态
通过React的useState钩子来管理展开和收起的状态,结合条件渲染实现功能。
import React, { useState } from 'react';
function ExpandCollapse() {
const [isExpanded, setIsExpanded] = useState(false);
const toggleExpand = () => {
setIsExpanded(!isExpanded);
};
return (
<div>
<button onClick={toggleExpand}>
{isExpanded ? '收起' : '展开'}
</button>
{isExpanded && <div>这里是展开的内容</div>}
</div>
);
}
export default ExpandCollapse;
使用CSS过渡动画
如果需要平滑的过渡效果,可以结合CSS实现动画。

import React, { useState } from 'react';
import './ExpandCollapse.css';
function ExpandCollapse() {
const [isExpanded, setIsExpanded] = useState(false);
const toggleExpand = () => {
setIsExpanded(!isExpanded);
};
return (
<div>
<button onClick={toggleExpand}>
{isExpanded ? '收起' : '展开'}
</button>
<div className={`content ${isExpanded ? 'expanded' : 'collapsed'}`}>
这里是展开的内容
</div>
</div>
);
}
export default ExpandCollapse;
对应的CSS文件:
.content {
overflow: hidden;
transition: max-height 0.3s ease;
}
.collapsed {
max-height: 0;
}
.expanded {
max-height: 500px; /* 根据内容调整 */
}
使用第三方库
如果需要更复杂的功能,可以考虑使用第三方库如react-collapse。

import React, { useState } from 'react';
import { Collapse } from 'react-collapse';
function ExpandCollapse() {
const [isExpanded, setIsExpanded] = useState(false);
const toggleExpand = () => {
setIsExpanded(!isExpanded);
};
return (
<div>
<button onClick={toggleExpand}>
{isExpanded ? '收起' : '展开'}
</button>
<Collapse isOpened={isExpanded}>
<div>这里是展开的内容</div>
</Collapse>
</div>
);
}
export default ExpandCollapse;
动态内容高度
如果内容高度不确定,可以通过动态计算高度实现更精确的展开收起效果。
import React, { useState, useRef, useEffect } from 'react';
function ExpandCollapse() {
const [isExpanded, setIsExpanded] = useState(false);
const [contentHeight, setContentHeight] = useState(0);
const contentRef = useRef(null);
useEffect(() => {
if (contentRef.current) {
setContentHeight(contentRef.current.scrollHeight);
}
}, []);
const toggleExpand = () => {
setIsExpanded(!isExpanded);
};
return (
<div>
<button onClick={toggleExpand}>
{isExpanded ? '收起' : '展开'}
</button>
<div
ref={contentRef}
style={{
overflow: 'hidden',
transition: 'max-height 0.3s ease',
maxHeight: isExpanded ? `${contentHeight}px` : '0',
}}
>
这里是展开的内容
</div>
</div>
);
}
export default ExpandCollapse;
多级展开收起
对于多级展开收起功能,可以通过嵌套组件或递归实现。
import React, { useState } from 'react';
function ExpandCollapseItem({ title, children }) {
const [isExpanded, setIsExpanded] = useState(false);
const toggleExpand = () => {
setIsExpanded(!isExpanded);
};
return (
<div>
<button onClick={toggleExpand}>
{isExpanded ? '收起' : '展开'} {title}
</button>
{isExpanded && <div>{children}</div>}
</div>
);
}
function MultiLevelExpandCollapse() {
return (
<div>
<ExpandCollapseItem title="一级标题">
<ExpandCollapseItem title="二级标题">
<div>这里是二级内容</div>
</ExpandCollapseItem>
</ExpandCollapseItem>
</div>
);
}
export default MultiLevelExpandCollapse;






