You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用ref获取child div宽高时宽度值异常问题

无法正确获取React子元素宽度问题

问题说明

需要获取类名为child的div的宽高,但通过ref获取到的宽度为991(实际应为602),高度显示正常。

组件结构

<Parent>
    <div className="child"></div>
</Parent>

已尝试的代码

export default class Parent extends React.Component<ParentProps, ParentState> {
    refComponent: React.RefObject<HTMLDivElement>;
    constructor(_props: ParentProps) {
        super(_props);
        this.refComponent = React.createRef();
    }

    componentDidMount() {
        const current = this.refComponent.current;

        if (current != null) {
            const clientRect = current.getBoundingClientRect();
            const height = clientRect.height;
            const width = clientRect.width;
        }
    }
}

子元素CSS样式

.child {
    background-color: green;
    width: 600px;
    height: 500px;
    border: solid black 1px;
    margin: 200px 100px 20px;
}

问题截图

元素尺寸显示截图

解决办法

1. 确认ref正确绑定到目标元素

当前组件结构中未将创建的refComponent绑定到child元素,这会导致ref获取的可能是父组件或其他元素的尺寸。修改组件结构:

<Parent>
    <div className="child" ref={this.refComponent}></div>
</Parent>

2. 延迟获取元素尺寸

如果元素尺寸依赖动态资源(如异步内容、字体加载),componentDidMount执行时元素可能未完全渲染。使用requestAnimationFrame延迟获取:

componentDidMount() {
    requestAnimationFrame(() => {
        const current = this.refComponent.current;
        if (current) {
            const { width, height } = current.getBoundingClientRect();
            console.log("正确尺寸:", width, height);
        }
    });
}

3. 检查盒模型计算

getBoundingClientRect()返回的尺寸包含border和padding(不包含margin),你的child元素设置width:600px+左右border各1px,总宽度应为602px,符合预期。若仍获取错误,需确认ref未指向其他元素。


内容的提问来源于stack exchange,提问作者Лейла

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 04:48:12