UNPKG

@enum-plus/plugin-react

Version:

A plugin for enum-plus that provides React components and hooks for enum handling

71 lines (70 loc) 1.97 kB
import { useEffect, useMemo, useRef, useState } from 'react'; // eslint-disable-next-line import/no-named-as-default import { getI18n, useTranslation } from 'react-i18next'; /** * - **EN:** A React component for rendering internationalized text using i18next. It listens for * language changes and updates the displayed text accordingly. * - **CN:** 一个用于渲染国际化文本的React组件,它监听语言变化并相应地更新显示的文本。 */ const ReactI18nextLocale = props => { const { i18nKey = '', useTranslationOptions, tOptions } = props; const useOptions = useMemo(() => { if (typeof useTranslationOptions === 'function') { return useTranslationOptions(); } else { return useTranslationOptions; } }, [i18nKey, useTranslationOptions]); const { t } = useTranslation(useOptions?.ns, useOptions); const getText = () => { return translate({ i18nKey, t, tOptions }); }; const getTextRef = useRef(getText); getTextRef.current = getText; const [text, setText] = useState(() => getText()); useEffect(() => { const instance = getI18n(); const handler = () => { setText(getTextRef.current()); }; instance.on('languageChanged', handler); return () => { instance.off('languageChanged', handler); }; }, []); return text; }; export function translate(props) { const { i18nKey, t, tOptions } = props; let options; if (typeof tOptions === 'function') { options = tOptions(i18nKey, t); } else { options = tOptions; } if (typeof options === 'string') { return options; } else if (options === undefined) { // eslint-disable-next-line import/no-named-as-default-member return t(i18nKey); } else { // eslint-disable-next-line import/no-named-as-default-member return t(i18nKey, options); } } export default ReactI18nextLocale; //# sourceMappingURL=ReactI18nLocale.js.map