背景
我尝试将组件的高度与浏览器的高度相匹配。
组件中有三幅图像,组件的高度大于浏览器的高度。
所以,我做了这个代码来匹配它们。
function Container({ children }: Props) {
const [maxWidth, setMaxWidth] = useState<string>('100%');
useEffect(() => {
const $app = document.querySelector('#root') as HTMLElement;
const $body = document.querySelector('body') as HTMLElement;
if (!$app || !$body) return;
const _maxWidth = Math.floor(
($body.clientHeight / $app.offsetHeight) * $app.clientWidth,
);
setMaxWidth(`${_maxWidth}px`);
}, []);
return (
<div className="container pt-10 pb-10" style={{ maxWidth }}>
{children}
</div>
);
}
export default Container;问题
但是,组件的宽度通常与预期不同。我认为高度没有正确计算,因为有一段时间来加载图像。在这种情况下我该怎么办?
这就是我现在所能想到的。
你有什么更好的主意吗?
发布于 2022-04-01 05:28:52
我认为你不必这样做才能完成你想要的。
如果您的目标是使您的容器尺寸与窗口尺寸相匹配,您应该考虑使用vw和vh单元。
然后,您可以设置您的图像尺寸,根据父只与css。根据您的最终模板,它们是几种实现此功能的方法。
这样的东西呢?
container {
display: flex;
flex-direction: row;
align-items: center;
}编辑:
关心视口单位,因为这些单位不是相对于你的父母,并可能导致不想要的行为。另一种方法是把你所有的父母都定在100%。
看看这个示例
发布于 2022-04-01 05:53:18
https://stackoverflow.com/questions/71702032
复制相似问题