我正在做的事情的一般想法是我有一个我创建的 React 组件,我在其中根据映射的动态数据渲染它。包装器 div 的高度为 100%,其中的子 div 将(理想情况下)根据每次渲染组件时计算的百分比占据 div 的垂直部分。
例如,一个组件被渲染并且与该组件关联的百分比是 70%。我想将那 70% 的值传递给 CSS,让它占据父 div 的 70%。
这不是我的确切代码,但它应该可以帮助您大致了解布局。
ReactJS
function Bucket({ numForChildDivHeight, numForParentDivHeight }) {
// to calculate the percentage of the child div, and set the --dynamic-height to that percentage
document.documentElement.style.setProperty('--dynamic-height',
numForChildDivHeight / numForParentDivHeight);
return (
<div className='parent-div'>
<div className='child-div'>
// misc. information
</div>
</div>
)
}
CSS
:root {
--dynamic-height: 0%;
}
.parent-div {
height: 100%;
}
.child-div {
height: var(--dynamic-height);
}
我遇到的问题是等式 (numForChildDivHeight / numForParentDivHeight) 返回双精度而不是百分比,因此 CSS 将其视为这样。有没有办法将 double 转换为百分比并将其传递给 CSS 变量?感谢您提供的任何帮助。
认为你可以做到这一点,
const element = document.getElementsByClassName("child-div");
element.style.height = (numForChildDivHeight / numForParentDivHeight) + '%';