子元素使用transform旋转后没有撑起父元素

发布时间 2023-03-24 17:53:53作者: ZerlinM

问题:

子元素使用transform:rotate(90deg) 旋转90度,并没有如愿的自动将父元素撑开宽高,那么,如何正常的撑开父元素(高宽对应)

思路:

在旋转后,我们可通过获取子元素当前的宽高,来赋值给父元素,那么,代码如下:
注意:需要注意的是,我们需要判断当前是否为已旋转,如果已旋转,那么就需要将子元素的宽赋值给父元素的高,因为子元素已经做了旋转,宽高互调。

js:

import React, { useState, useEffect, useRef } from 'react';
import { Button } from 'antd';
import styles from './index.less';

export default function RotateBox() {
    const [rotateDeg, setRotateDeg] = useState(0)
    const [viewWidth, setViewWidth] = useState()
    const [viewHeight, setViewHeight] = useState()

    const containerRef = useRef(null);

    const rotatePage = (type) => {
        console.log('typp', type)
        if (type === 'LEFT') {
            setRotateDeg(rotateDeg - 90)
        } else {
            setRotateDeg(rotateDeg + 90)
        }
    }

    useEffect(() => {
        // const width = Math.abs(rotateDeg % 180) === 90 ? containerRef.current.offsetHeight : containerRef.current.offsetWidth
        const height = Math.abs(rotateDeg % 180) === 90 ? containerRef.current.offsetWidth : containerRef.current.offsetHeight
        // setViewWidth(width);
        setViewHeight(height);
    }, [rotateDeg])

    return (
        <div className={styles.content}>
            <div className={styles.box} style={{
                // width: viewWidth,
                height: viewHeight
            }}>
                <div ref={containerRef} className={styles['box-rotate']} style={{ transform: `rotate(${rotateDeg}deg)` }} />
            </div>
            <div className={styles.btns}>
                <Button onClick={() => rotatePage('LEFT')}>向左旋转</Button>
                <Button onClick={() => rotatePage('RIGHT')}>向右旋转</Button>
            </div>
        </div>
    )
}

css:

.content {
  width: 100%;

  .box {
    width: 100%;
    min-width: 100px;
    min-height: 100px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #eee;
    overflow: hidden;

    &-rotate {
      width: 100%;
      height: 30px;
      background-color: #aaa;
    }
  }

  .btns {
    width: 100%;
    text-align: center;
  }
}