React中的测量组件大小与外部样式表不一致

问题描述 投票:0回答:1

我使用简单的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已经启动。把它移到componentDidUpdatecomponentDidMount没有任何区别,这是有道理的。 DOM已加载,样式不是....

解决这个问题的正确方法是什么?有没有办法检查样式表是否加载它是否有效?

reactjs dom stylesheet dimensions
1个回答
0
投票

我想我只是通过将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>
        )
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.