如何在React中不使用getElementById与getBoundingClientRect获取组件位置
解决方案
场景1:所有布局参数为可控的硬编码/状态值
你当前的示例代码所有定位、尺寸参数都是手动定义的,完全不需要访问DOM,直接把这些值抽离为可计算的变量,渲染前就能拿到结果:
// 抽离所有布局参数为统一数值变量(单位统一为px) const BASE_BOX_STYLE = { top: 100, left: 100, width: 500, height: 500 } const CHILD_BOX_STYLE = { top: 150, left: 150, width: 200, height: 200 } export function TestPage() { // 直接计算父元素顶部到子元素底部的距离:子元素相对于父的top偏移 + 子元素高度 const targetDistance = CHILD_BOX_STYLE.top + CHILD_BOX_STYLE.height console.log('计算得到的距离:' + targetDistance + 'px') // 渲染前就能得到350px的结果 return <BaseObject />; } function BaseObject() { return ( <div className="popBox" style={{ top: `${BASE_BOX_STYLE.top}px`, left: `${BASE_BOX_STYLE.left}px`, width: `${BASE_BOX_STYLE.width}px`, height: `${BASE_BOX_STYLE.height}px` }} > <div className="popBox2" style={{ top: `${CHILD_BOX_STYLE.top}px`, left: `${CHILD_BOX_STYLE.left}px`, width: `${CHILD_BOX_STYLE.width}px`, height: `${CHILD_BOX_STYLE.height}px` }} ></div> </div> ); }
配套CSS不需要修改:
.popBox { background-color: #4F8989; position: sticky; } .popBox2 { background-color: #89694f; position: sticky; }
场景2:布局参数存在动态内容
如果存在文本长度不固定、用户可调整尺寸等不可提前预知的场景,不需要用getElementById或getBoundingClientRect,可以通过ResizeObserver配合React Ref实现自动计算:
import { useRef, useState, useEffect } from 'react' export function TestPage() { const [targetDistance, setTargetDistance] = useState(0) // 直接使用状态值,尺寸变化会自动更新 console.log('当前距离:' + targetDistance + 'px') return <BaseObject onDistanceUpdate={setTargetDistance} />; } function BaseObject({ onDistanceUpdate }) { const childRef = useRef(null) useEffect(() => { const observer = new ResizeObserver((entries) => { const childEntry = entries[0] // 直接从ResizeObserver回调取尺寸,offsetTop为子元素相对于父元素的顶部偏移 const distance = childRef.current.offsetTop + childEntry.contentRect.height onDistanceUpdate(distance) }) observer.observe(childRef.current) return () => observer.disconnect() }, [onDistanceUpdate]) return ( <div className="popBox" style={{ top: "100px", left: "100px", width: "500px", height: "500px" }} > <div ref={childRef} className="popBox2" style={{ top: "150px", left: "150px", width: "200px", height: "200px" }} ></div> </div> ); }
内容的提问来源于stack exchange,提问作者David Owen
相关产品推荐
相关产品推荐

