本文主要是介绍Collapse折叠面板组件实现思路,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
折叠面板组件实现思路:
参考链接:https://element.eleme.cn/#/zh-CN/component/collapse
核心思路:内外两层div,外层div设置overflow:hidden; 并动态设置外层div高度,高度根据内层div的offsetHeight
// Collapse.jsx
/*** 核心思路:内外两层div,外层div设置overflow:hidden; 并动态设置外层div高度,高度根据内层div的offsetHeight*/
import React, { useEffect, useRef } from 'react';
function Collapse({ children, open }) {const ref = useRef(null);const contentRef = useRef(null);useEffect(() => {updateSize();}, [open]);const updateSize = () => {ref.current.style.setProperty('height', `${open ? contentRef.current.offsetHeight : 0}px`);};return (<><div ref={ref} className={`collapse ${open ? 'show' : 'hidden'}`}><div ref={contentRef} className='content'>{children}</div></div></>);
}
export default Collapse;
// App.jsx
import React, { useState } from 'react';
import Collapse from './Collapse';
import './style.scss';
function App() {const [unfold, setUnfold] = useState(false);const [unfold2, setUnfold2] = useState(false);return (<><div className='title' onClick={() => setUnfold(!unfold)}>menu1</div><Collapse open={unfold}><div><ul><li>hello</li><li>hello</li><li>hello</li></ul></div></Collapse><div className='title' onClick={() => setUnfold2(!unfold2)}>menu2</div><Collapse open={unfold2}><div><ul><li>word</li><li>word</li><li>word</li><li>word</li><li>word</li><li>word</li><li>word</li><li>word</li><li>word</li><li>word</li></ul></div></Collapse></>);
}
export default App;
.collapse {ul {list-style: none;margin: 0;}overflow: hidden;&.show {transition: height 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);}&.hidden {transition: height 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);}
}
.title {background-color: #ccc;
}
效果图:
这篇关于Collapse折叠面板组件实现思路的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!