如何使用 react 和样式组件制作手风琴菜单



我正在尝试创建一个手风琴菜单,就像Bootstrap https://getbootstrap.com/docs/4.3/components/collapse/

我已经设法让它打开和关闭正常,但我错过了平稳过渡:/

就像没有应用过渡一样。

import React, { useState } from 'react';
import styled from 'styled-components';
import { Button } from './common/button';
const AccordionWrapper = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
background-color: var(--Secondary-color-dark);
border-radius: 10px;
height: auto;
padding: 2%;
text-align: center;
transition: all 0.6s ease-in-out;
`;
const InternalWrapper = styled.div`
width: 100%;
max-height: ${(props) => (props.open ? '100%' : '0')};
transition: all 1s ease-in-out;
overflow: hidden;
`;
const Accordion = ({ title, subTitle, btnText }) => {
const [ open, setOpen ] = useState(false);
const handleClick = () => {
setOpen(!open);
};
return (
<AccordionWrapper>
<h2>{title}</h2>
<h3>{subTitle}</h3>
<InternalWrapper open={open}>
<h1>Hello</h1>
</InternalWrapper>
<Button padding="5px" onClick={handleClick}>
{btnText}
</Button>
</AccordionWrapper>
);
};
Accordion.defaultProps = {
title    : 'title',
subTitle : 'subtitle',
btnText  : 'Read more >>'
};
export default Accordion;

这是一个代码笔复制品。 https://codepen.io/hichihachi/pen/MWwKZEO?editors=0010

任何帮助将不胜感激,谢谢。

当您以百分比和其他一些单位设置最大高度过渡时,最大高度过渡不起作用。要使过渡工作,您可以定义类似的东西

max-height: ${(props) => (props.open ? '100px' : '0')};

https://codepen.io/alonabas/pen/PoqNYLR?editors=1111

但是,如果您的内容高度超过 100px,当您打开手风琴时,内容将被剪切。在这种情况下,您可以使用 jQuery 来计算内容的确切大小,或者使用最大高度的某个最大可能值。

此处介绍了这两个选项: https://stackoverflow.com/a/8331169/2916925

最新更新