测量元素:useRef 与 useCallback

问题描述

当我必须测量特定节点的大小、位置或属性时,什么是最正确的(根据 React 文档)“保存”其引用的方法useRef 还是 useCallback

通常,当我必须根据滚动位置更新对象的位置时,我通常会这样做:

const myRef= useRef(null);
const [divTop,setDivTop] = useState(0);

useEffect(()=>{
function doSomethingWithScrollPosition(){
 if(myRef.current){
   setDivTop(window.scrollY-myRef.current.getBoundingClientRect().top) //Just random operat. using ref
 }
}

window.addEventListener('scroll',doSomethingWithScrollPosition)
return ()=>window.removeEventListener('scroll',doSomethingWithScrollPosition)
},[myRef])

return(
  <div ref={myRef}>
  </div>
)

但是最近我最终阅读了与测量节点参数相关的文档,其中建议使用 useCallback (React docs: How can I measure a DOM node?)。

使用 useCallback 总是更好还是存在两种解决方案都可行的情况?在某些情况下应该首选 useRef

我应该将我的代码重构为这样的吗?

const myRefCallback= useCallback(node=>setNode(node),[]); 
const [node,setNode] = useState(null);
const [divTop,setDivTop] = useState(0);

useEffect(()=>{
function doSomethingWithScrollPosition(){
 if(node){
   setDivTop(window.scrollY-node.getBoundingClientRect().top) //Just random operat. using ref
 }
}

window.addEventListener('scroll',[node])

return(
  <div ref={myRefCallback}>
  </div>
)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)