如何使用React.useRef获得实际的Dom节点? Element.getBoundingClientRect()对useRef变量不起作用

时间:2020-03-07 04:48:03

标签: javascript reactjs dom react-hooks

我正在尝试使用Element.getBoundingClientRect()来获取dom元素的x,y,顶部,左侧值。

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()函数 第二个editorRef.current是useRef所提供的,它没有getBoundingClientRect()函数。

enter image description here

我只想知道如何将useBoundingClientRect()函数与useRef()一起使用

1 个答案:

答案 0 :(得分:1)

很可能您的editorRef指向的是React组件,而不是DOM元素。你可以得到这样的元素

var element=ReactDOM.findDOMNode(editorRef.current);
var rect =element.getBoundingClientRect();

但是在严格模式下不建议使用ReactDOM.findDOMNode(建议使用)

<React.StrictMode></React.StrictMode>

更好的方法是,如果您有权访问子组件,则使用forwardRef,另一种选择是使用包装div的方法,该div包装子组件并像这样使用useRef

<div ref={editorRef} >
<ChildComp/>
</div> 

这将允许您访问getBoundingClientRect()可能返回错误的大小(rect.top 0,rect.height 0等),在这种情况下,您需要延迟调用它

useEffect(() => {

setTimeout(() => {
   var rect = editorRef.current.getBoundingClientRect();
}, 300);

  }, [ ]);