echoes/frontend/hooks/createServiceContext.tsx

56 lines
1.6 KiB
TypeScript
Raw Normal View History

// File path: /hooks/createServiceContext.tsx
import { createContext, ReactNode, useContext } from "react";
/**
* 使
*
* @param name -
* @param getInstance -
* @returns Provider useService
*/
interface ServiceContextResult<T> {
Provider: React.FC<{ children: ReactNode }>; // 提供服务实例的组件
useService: () => T; // 获取服务实例的钩子
}
/**
*
*
* @param name -
* @param getInstance -
* @returns Provider useService
*/
export function createServiceContext<T>(
name: string,
getInstance: () => T
): ServiceContextResult<T> {
// 创建一个上下文,初始值为 undefined。
const ServiceContext = createContext<T | undefined>(undefined);
// Provider 组件,用于提供服务实例给子组件
const Provider = ({ children }: { children: ReactNode }) => {
const service = getInstance();
return (
<ServiceContext.Provider value={service}>
{children}
</ServiceContext.Provider>
);
};
// 获取服务实例的钩子
const useService = (): T => {
const context = useContext(ServiceContext);
if (context === undefined) {
throw new Error(`use${name} must be used within a ${name}Provider`);
}
return context;
};
return {
Provider,
useService,
};
}