首页 > 解决方案 > 我无法将添加的高度固定到组件中

问题描述

我正在使用 material-ui 和 sass 在 react.js 项目中工作。我需要创建像 ChatBit 组件这样的组件,然后我在它发布时编写它。

customComponent.js 文件。

    // @flow
    import * as React from 'react';
    import { useState } from 'react';
    import { Avatar} from "@material-ui/core";
    import useStyle from './styles';

    type Props = {
        children: React.Node;
    }

    const AbsoluteBox = ({
        children
    }: Props) => {
        const [toggled, setToggled] = useState(false);
        const styles = useStyle();
        const handleClick = () => {
            setToggled(!toggled);
        };
        const contentStyle = `container__content_${toggled ? 'show': 'hide'}`;
        return (
            <div className={styles.container__bottomRight}>
                <div className={styles.container__header} onClick={handleClick}>
                    <Avatar
                        variant="rounded"
                        src="/assets/images/rebots.svg"
                className={styles.container__header__avatar}
                    />
                </div>
                <div
                    className={styles[contentStyle]}
                >
                    {children}
                </div>
            </div>
        );
    };

    export default AbsoluteBox;

样式.js 文件。

    import { makeStyles } from '@material-ui/core';

    export default makeStyles({
        container__bottomRight: {
            position: 'fixed',
            right: 0,
            bottom: 0,
            marginRight: 12,
            width: 300,
            borderTopLeftRadius: 10,
            borderTopRightRadius: 10,
            boxShadow: '0px 0px 13px 0px rgba(0,0,0,0.51)'
        },
        container__header: {
            paddingLeft: 10,
            paddingTop: 4,
            paddingBottom: 6,
            backgroundColor: '#D7E0FC',
            height: 38,
            borderTopLeftRadius: 8,
            borderTopRightRadius: 8,
            cursor: 'pointer'
        },
        container__header__avatar: {
            height: 40
        },
        container__content_hide: {
            transition: 'height 400ms 400ms, opacity 400ms 0ms',
            opacity: 0.0,
            height: 0,
        },
        container__content_show: {
            height: 400,
            opacity: 1.0,
            boxSizing: 'border-box',
            transition: 'height 400ms 0ms, opacity 400ms 400ms',
        },
    });

然后我这样调用组件:

    <AbsoluteBox>
      <h1>Hello World</h1>
    </AbsoluteBox>

所以我发现的问题是当我打开盒子时,一切都是正确的,但是当我需要关闭它时,我不知道它来自哪里的空白。

在此处输入图像描述

在此处输入图像描述

标签: javascriptcsssassmaterial-uireactjs

解决方案


框内的<h1>标签有边距,这会导致这些问题(即使包含的高度设置为 0,也会产生边距)。

您可以通过将 h1 元素的 margin-top 设置为 0 来解决此问题(或使用其他一些元素并相应地设置它们的样式)。


推荐阅读