简体   繁体   English

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

[英]How to make accordion menu using react & styled components

I'm trying to create an accordion menu like the one from Bootstrap https://getbootstrap.com/docs/4.3/components/collapse/我正在尝试创建一个类似于 Bootstrap 的手风琴菜单https://getbootstrap.com/docs/4.3/components/collapse/

I have managed to get it to open and close fine, but I'm missing the smooth transition :/我已经设法让它正常打开和关闭,但我错过了平稳过渡:/

It's like the transition is just not being applied.就像没有应用过渡一样。

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;

Here is a codepen reproduction.这是一个codepen复制品。 https://codepen.io/hichihachi/pen/MWwKZEO?editors=0010 https://codepen.io/hichihachi/pen/MWwKZEO?editors=0010

Any help would be appreciated, thanks.任何帮助将不胜感激,谢谢。

Max-height transition doesn't work when you set it in percentage and in some other units.当您以百分比和其他一些单位设置时,最大高度过渡不起作用。 To make the transition work you can define something like为了使过渡工作,您可以定义类似

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

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

But if your content is more than 100px in height, when you open the Accordion the content will be cut.但是如果您的内容高度超过 100 像素,当您打开手风琴时,内容将被剪切。 In this case you can use jQuery to calculate the exact size of your content or use some maximal possible value of max-height.在这种情况下,您可以使用 jQuery 来计算您的内容的确切大小或使用 max-height 的一些最大可能值。

Both options are described here: https://stackoverflow.com/a/8331169/2916925此处描述了这两个选项: https : //stackoverflow.com/a/8331169/2916925

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM