我正在尝试使用 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() 一起使用