Files
frontend/src/hooks/responsive/useResponsiveValue.ts

43 lines
1.3 KiB
TypeScript
Raw Normal View History

/**
* Hook
*/
import { useMemo } from 'react';
import { useBreakpoint } from './useBreakpoint';
import { ResponsiveValue, FineBreakpointKey, REVERSE_BREAKPOINT_ORDER } from './constants';
/**
*
*
* @param value -
* @returns
*
* @example
* const padding = useResponsiveValue({ xs: 8, md: 16, lg: 24 });
* // 在 xs 屏幕返回 8md 屏幕返回 16lg 及以上返回 24
*/
export function useResponsiveValue<T>(value: ResponsiveValue<T>): T {
const { fineBreakpoint } = useBreakpoint();
return useMemo(() => {
// 如果不是对象,直接返回
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
return value as T;
}
const valueMap = value as Partial<Record<FineBreakpointKey, T>>;
// 从当前断点开始向下查找
const currentIndex = REVERSE_BREAKPOINT_ORDER.indexOf(fineBreakpoint);
for (let i = currentIndex; i < REVERSE_BREAKPOINT_ORDER.length; i++) {
const bp = REVERSE_BREAKPOINT_ORDER[i];
if (bp in valueMap) {
return valueMap[bp]!;
}
}
// 如果没找到,返回 xs 的值或第一个值
return (valueMap.xs ?? Object.values(valueMap)[0]) as T;
}, [value, fineBreakpoint]);
}