小编byy*_*ung的帖子

如何使用 React.useRef 获取实际的 Dom 节点?Element.getBoundingClientRect() 不适用于 useRef 变量

我正在尝试使用 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 
Run Code Online (Sandbox Code Playgroud)

所以我尝试通过查询选择节点来尝试这种方法

const editorNodebyQuery =document.querySelectorAll(".DraftEditor-root")[0];
const editorNodebyQueryRect = editorNodebyQuery.getBoundingClientRect() // work well!! 
Run Code Online (Sandbox Code Playgroud)

但我不喜欢通过查询访问dom节点..我认为它很重..我想使用useRef。

第一个 rootEditorNode 是我通过 querySelector 得到的,它有 getBoundingClientRect() 函数;第二个 editorRef.current 是我通过 useRef 得到的,它没有 getBoundingClientRect() 函数。

在此输入图像描述

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

javascript dom reactjs react-hooks

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

dom ×1

javascript ×1

react-hooks ×1

reactjs ×1