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,提问作者Лейла
相关产品推荐
相关产品推荐

