我使用简单的refCallback来测量组件的大小:
<div className="wrapper" ref={(el) => console.log(el.getBoundingClientRect())}>Lorem....</div>
与Chrome Dev Tools相比,这给出了错误的结果,所以我开始挖掘并发现如果我没有在我的组件中加载我的App.scss
它在控制台中显示正确的大小。
所以经过简单的检查,我从App.scss
中删除了所有样式,并且只添加了:
.wrapper { margin: 0; }
我看到boundingClientRect再次出错了。
这与Webpack有关,我认为加载JS的地方应用了样式。但是,refCallback已经启动。把它移到componentDidUpdate
或componentDidMount
没有任何区别,这是有道理的。 DOM已加载,样式不是....
解决这个问题的正确方法是什么?有没有办法检查样式表是否加载它是否有效?
我想我只是通过将document.body.onload
添加到componentDidMount
并在回调中处理大小来解决它。
import '~/somestyles.scss'
class SizeContainer extends React.Component<IProps, any> {
private ref = React.createRef<HTMLDivElement>();
componentDidMount(): void {
document.body.onload = this.onLoad
}
onLoad = () => {
if (this.ref.current) {
const els = Array.from(this.ref.current!.childNodes);
els.forEach(el => {
console.log((el as Element).getBoundingClientRect())
})
}
};
render() {
const { children } = this.props;
return (
<div ref={this.ref}>
{ children }
</div>
)
}
}