需求:
有一个组件中有两个ref,一个f是orwardRef暴露出的ref,另一个是内部维护的ref
如何将这个两个ref都赋到 一个element上?
const Element = forwardRef((props, ref) => {
const insiderRef = useRef(null);
return (
<div></div>
)
})
解决方案:
????????ref可以接收一个回调函数,这个回调函数在组件挂载或者卸载的时候被调用,函数参数为组件实例或DOM元素。
可以利用此机制,实现一个函数为两个ref赋值。
hooks实现如下:
import { MutableRefObject, Ref, useMemo } from 'react';
function setRef<T>(
ref: MutableRefObject<T | null> | ((instance: T | null) => void) | null | undefined,
value: T | null,
): void {
if (typeof ref === 'function') {
ref(value);
} else if (ref) {
ref.current = value;
}
}
export default function useForkRef<InstanceA, InstanceB>(
refA: Ref<InstanceA> | null | undefined,
refB: Ref<InstanceB> | null | undefined,
): Ref<InstanceA & InstanceB> | null {
/**
* This will create a new function if the ref props change and are defined.
* This means react will call the old forkRef with `null` and the new forkRef
* with the ref. Cleanup naturally emerges from this behavior.
*/
return useMemo(() => {
if (refA == null && refB == null) {
return null;
}
return (refValue) => {
setRef(refA, refValue);
setRef(refB, refValue);
};
}, [refA, refB]);
}
|