File size: 1,285 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
// Proxy the dom ref with `{ nativeElement, otherFn }` type
// ref: https://github.com/ant-design/ant-design/discussions/45242
import { useImperativeHandle } from 'react';
import type { Ref } from 'react';
function fillProxy(
element: HTMLElement & { _antProxy?: Record<string, any> },
handler: Record<string, any>,
) {
element._antProxy = element._antProxy || {};
Object.keys(handler).forEach((key) => {
if (!(key in element._antProxy!)) {
const ori = (element as any)[key];
element._antProxy![key] = ori;
(element as any)[key] = handler[key];
}
});
return element;
}
export default function useProxyImperativeHandle<
NativeELementType extends HTMLElement,
ReturnRefType extends { nativeElement: NativeELementType },
>(ref: Ref<any> | undefined, init: () => ReturnRefType) {
return useImperativeHandle(ref, () => {
const refObj = init();
const { nativeElement } = refObj;
if (typeof Proxy !== 'undefined') {
return new Proxy(nativeElement, {
get(obj: any, prop: any) {
if ((refObj as any)[prop]) {
return (refObj as any)[prop];
}
return Reflect.get(obj, prop);
},
});
}
// Fallback of IE
return fillProxy(nativeElement, refObj);
});
}
|