Javascript 如何使用React.useRef获取实际的Dom节点?元素。getBoundingClientRect()不处理useRef变量
我正在尝试使用Element.getBoundingClientRect()获取dom元素的x、y、top、left值Javascript 如何使用React.useRef获取实际的Dom节点?元素。getBoundingClientRect()不处理useRef变量,javascript,reactjs,dom,react-hooks,Javascript,Reactjs,Dom,React Hooks,我正在尝试使用Element.getBoundingClientRect()获取dom元素的x、y、top、left值 const editorRef = useRef() ... // attatched editor ref on the dom element that I'm interested ... editorRef.current.focus() // works well const editorNodeRect = editorRef.current.getBound
const editorRef = useRef()
... // attatched editor ref on the dom element that I'm interested
...
editorRef.current.focus() // works well
const editorNodeRect = editorRef.current.getBoundingClientRect() // got error saying getBoundingClientRect() is not a function
因此,我通过查询选择节点来尝试这种方法
const editorNodebyQuery =document.querySelectorAll(".DraftEditor-root")[0];
const editorNodebyQueryRect = editorNodebyQuery.getBoundingClientRect() // work well!!
但是我不喜欢通过查询访问dom节点。。我认为它很重。。
我想使用useRef
第一个rootEditorNode是我通过querySelector得到的,它有getBoundingClientRect()函数
second editorRef.current是我通过useRef得到的,它没有getBoundingClientRect()函数
我只是想知道如何将getBoundingClientRect()函数与useRef()一起使用。很可能您的editorRef指向的是React组件,而不是DOM元素。你可以得到这样的元素
var element=ReactDOM.findDOMNode(editorRef.current);
var rect =element.getBoundingClientRect();
<div ref={editorRef} >
<ChildComp/>
</div>
但在严格模式下不推荐使用ReactDOM.findDOMNode(建议使用)
你能提供完整的相关代码吗?您描述的策略应该可以很好地工作(如本文所示)。
<div ref={editorRef} >
<ChildComp/>
</div>
useEffect(() => {
setTimeout(() => {
var rect = editorRef.current.getBoundingClientRect();
}, 300);
}, [ ]);