美文网首页
useControl

useControl

作者: 飞飞廉 | 来源:发表于2024-01-25 10:48 被阅读0次
    export function useControl(CompIn) {
        const ref = useRef();
        // 通过 proxy 实现支持各种方法名
        const methods = useMemo(() => createMethodsProxy(ref), []);
        const CompOut = useMemo(() => {
            if (!CompIn) {
                return null;
            }
            const ControlledComp = function ControlledComp(props) {
                return <CompIn {...props} ref={ref} />;
            };
            if (process.env.NODE_ENV === 'development') {
                const originalName = CompIn.displayName ?? CompIn.name ?? 'Unknown';
                ControlledComp.displayName = `useControl(${originalName})`;
            }
            return ControlledComp;
        }, [CompIn]);
        return [CompOut, methods];
    }
    
    function createMethodsProxy(ref) {
        return new Proxy(
            {
                $get(property) {
                    return ref.current?.[property];
                },
            },
            {
                get(target, property) {
                    if (target[property]) {
                        return target[property];
                    }
                    const method = async (...args) => {
                        const fn = ref.current?.[property];
                        const value = fn && await fn(...args);
                        return value;
                    };
                    target[property] = method;
                    return method;
                },
            }
        );
    }
    
    

    相关文章

      网友评论

          本文标题:useControl

          本文链接:https://www.haomeiwen.com/subject/qmfdodtx.html