有一个组件中有两个ref,一个f是orwardRef暴露出的ref,另一个是内部维护的ref
如何将这个两个ref都赋到 一个element上?
const Element = forwardRef((props, ref) => {
const insiderRef = useRef(null);
return (
)
})
解决方案:
ref可以接收一个回调函数,这个回调函数在组件挂载或者卸载的时候被调用,函数参数为组件实例或DOM元素。
可以利用此机制,实现一个函数为两个ref赋值。
hooks实现如下:import { MutableRefObject, Ref, useMemo } from 'react';
function setRef(
ref: MutableRefObject | ((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(
refA: Ref | null | undefined,
refB: Ref | null | undefined,
): Ref | 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]);
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)