使用回调分配 React ref 与直接设置它之间的区别?

Difference between assigning React ref using a callback versus setting it directly?

它的工作原理和行为相同,但想知道直接设置 ref 与通过将元素作为参数的回调设置 ref 是否有任何实际差异。

给出这个反应挂钩组件:

const myComponent = ({ ...props}) => {
  const myRef = React.useRef(null);

  ...

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

对比

const myComponent = ({ ...props}) => {
  const myRef = React.useRef(null);

  ...

  return (
    <div>
      ref={element => {
        myRef.current = element;        
      }}
    </div>
  )
}

根据 useRef 文档,两者相似:

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).

因此,第一个代码示例将与第二个代码示例完全一样。

除了

If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

意思;如果你想重新渲染组件,那么你可以使用回调 ref.


来自 docs 本身的最佳示例:

测量DOM节点的位置或大小

function MeasureExample() {
  const [height, setHeight] = useState(0);

  const measuredRef = useCallback(node => {
    if (node !== null) {
      setHeight(node.getBoundingClientRect().height);
    }
  }, []);

  return (
    <>
      <h1 ref={measuredRef}>Hello, world</h1>
      <h2>The above header is {Math.round(height)}px tall</h2>
    </>
  );
}

因此,您可以发现元素的高度将通过使用回调 ref 来更改。如果您没有使用回调引用,那么它就不会被重新渲染,也不会更新任何内容高度。

好吧,使用第一种方法,您无法在其内容更改时通知,更改 .current 属性 不会重新呈现它,但是使用 callback ref 您可以 运行 一些代码,基于您的用例,当 React 将 ref 附加或分离到 DOM 节点时。

对于回调方法,您确实不需要使用 useRef,而是可以使用 useCallback。这是 React 文档中的示例:

function MeasureExample() {
  const [height, setHeight] = useState(0);

  const measuredRef = useCallback(node => {
  if (node !== null) {
     setHeight(node.getBoundingClientRect().height);
  }
  }, []);

    return (
   <>
     <h1 ref={measuredRef}>Hello, world</h1>
     <h2>The above header is {Math.round(height)}px tall</h2>
   </>
 );
}