【发布时间】:2020-11-20 16:58:56
【问题描述】:
基于我看到的其他解决方案,我创建了一个组件,该组件应该计算其子项的宽度和高度,然后将宽度和高度设置为等于长度中的任何一个一个更长。
- Ex.如果width=30,height=20,则设置width和height为30。如果height为30,width为20,结果应该是一样的。
import React, {useState, useEffect, useRef} from 'react';
const SymmetricalDiv = ({style, children, ...props}) => {
const [diamStyle, setDiamStyle] = useState({});
const elementRef = useRef(null);
style = style ? Object.assign({}, diamStyle, style) : diamStyle ;
useEffect(() => {
const width = elementRef.current.clientWidth;
const height = elementRef.current.clientHeight;
const diam = Math.max(width, height);
setDiamStyle({width: diam, height: diam});
}, []);
return (
<div ref={elementRef} {...props} style={style}>
{children}
</div>
);
};
这是我尝试使用此组件的示例。 (样式是使用引导程序完成的)
import React from 'react';
import {SymmetricalDiv} from 'components/Styled'
import svgLogo from 'src/SVG_logo.svg'
const MyComponent = () => {
return (
<SymmetricalDiv className='rounded-circle d-flex flex-column align-items-center bg-danger'>
<strong >A title</strong>
<span>A description</span>
<img className='my-3' src={svgLogo} />
<a href="#">A Link</a>
</SymmetricalDiv>
);
};
此示例产生以下结果。它错误地计算了高度,并认为宽度是较长的尺寸。然后将宽度和高度设置为等于宽度,这就是为什么一些孩子出现在圆圈之外的原因。
【问题讨论】:
-
也将样式设置为状态。
-
@WilliamWang 这不会改变任何事情,对不起
标签: javascript reactjs twitter-bootstrap react-hooks use-ref