2020-06-05 18:06:52 +08:00
|
|
|
import { composeRef } from 'rc-util/lib/ref';
|
2023-05-05 20:52:44 +08:00
|
|
|
import React from 'react';
|
2020-06-05 18:06:52 +08:00
|
|
|
import { FormContext } from '../context';
|
2022-05-07 14:31:54 +08:00
|
|
|
import type { InternalNamePath } from '../interface';
|
2020-06-05 18:06:52 +08:00
|
|
|
|
|
|
|
export default function useItemRef() {
|
|
|
|
const { itemRef } = React.useContext(FormContext);
|
|
|
|
const cacheRef = React.useRef<{
|
|
|
|
name?: string;
|
|
|
|
originRef?: React.Ref<any>;
|
|
|
|
ref?: React.Ref<any>;
|
|
|
|
}>({});
|
|
|
|
|
|
|
|
function getRef(name: InternalNamePath, children: any) {
|
|
|
|
const childrenRef: React.Ref<React.ReactElement> =
|
|
|
|
children && typeof children === 'object' && children.ref;
|
|
|
|
const nameStr = name.join('_');
|
|
|
|
if (cacheRef.current.name !== nameStr || cacheRef.current.originRef !== childrenRef) {
|
|
|
|
cacheRef.current.name = nameStr;
|
|
|
|
cacheRef.current.originRef = childrenRef;
|
|
|
|
cacheRef.current.ref = composeRef(itemRef(name), childrenRef);
|
|
|
|
}
|
|
|
|
|
|
|
|
return cacheRef.current.ref;
|
|
|
|
}
|
|
|
|
|
|
|
|
return getRef;
|
|
|
|
}
|