ant-design/components/locale-provider/LocaleReceiver.tsx

66 lines
2.1 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
import defaultLocaleData from './default';
import LocaleContext from './context';
import { Locale } from '.';
2021-06-03 09:36:04 +08:00
export interface LocaleReceiverProps<C extends keyof Locale = keyof Locale> {
componentName: C;
defaultLocale?: Locale[C] | (() => Locale[C]);
children: (locale: Exclude<Locale[C], undefined>, localeCode?: string, fullLocale?: object) => React.ReactNode;
}
2021-06-03 09:36:04 +08:00
export default class LocaleReceiver<C extends keyof Locale = keyof Locale> extends React.Component<LocaleReceiverProps<C>> {
static defaultProps = {
componentName: 'global',
};
static contextType = LocaleContext;
2021-06-03 09:36:04 +08:00
getLocale(): Exclude<Locale[C], undefined> {
const { componentName, defaultLocale } = this.props;
2021-06-03 09:36:04 +08:00
const locale =
defaultLocale || defaultLocaleData[componentName ?? 'global'];
const antLocale = this.context;
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
return {
2021-06-03 09:36:04 +08:00
...(locale instanceof Function ? locale() : locale),
...(localeFromContext || {}),
};
}
getLocaleCode() {
const antLocale = this.context;
const localeCode = antLocale && antLocale.locale;
// Had use LocaleProvide but didn't set locale
if (antLocale && antLocale.exist && !localeCode) {
return defaultLocaleData.locale;
}
return localeCode;
}
render() {
return this.props.children(this.getLocale(), this.getLocaleCode(), this.context);
}
}
type LocaleComponent = keyof Locale;
export function useLocaleReceiver<T extends LocaleComponent>(
componentName: T,
defaultLocale?: Locale[T] | Function,
): [Locale[T]] {
const antLocale = React.useContext(LocaleContext);
const componentLocale = React.useMemo(() => {
const locale = defaultLocale || defaultLocaleData[componentName || 'global'];
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
2020-08-22 22:31:20 +08:00
return {
2020-08-22 22:31:20 +08:00
...(typeof locale === 'function' ? (locale as Function)() : locale),
...(localeFromContext || {}),
};
}, [componentName, defaultLocale, antLocale]);
return [componentLocale];
}