我正在使用i18next使用 typescript 并使用 i18next-resources-for-ts 的翻译资源从 JSON 生成资源类型。一切正常,但在使用带有 useTranslation()
Hook 中的 t
函数的前缀命名空间时遇到问题。我不是在寻找 useTranslation('common')
或 t('auth.login.text', { ns: 'common' })
,它工作正常并且是输入正确。
这是我的 i18next.d.ts
的简化版本:
import 'i18next';
import common from '../public/locales/en/common.json';
const resources = {
common,
} as const;
declare module 'i18next' {
interface CustomTypeOptions {
returnNull: false;
defaultNS: 'common';
resources: typeof resources;
}
}
并设置i18next.ts
import commonDe from '../public/locales/de/common.json';
import commonEn from '../public/locales/de/common.json';
import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
const resources = {
de: {
common: commonDe,
},
en: {
common: commonEn,
},
};
export const defaultNS = 'common';
i18next
.use(initReactI18next)
.init({
resources,
ns: [defaultNS],
defaultNS,
lng: 'en',
interpolation: {
escapeValue: false,
},
returnNull: false,
});
export default i18next;
尝试在 t
函数中使用前缀命名空间时会出现问题:
const { t } = useTranslations();
t('common:auth.login.text')
然后类型不起作用。
我知道我可以指定 ns
作为 t
函数的选项,或者在 useTranslation
Hook 中选择它。但我也想在翻译键中支持上面的前缀方式。
任何有关如何实现这一目标的建议或想法将不胜感激。谢谢!
最佳答案
这并不是真正关于i18next-resource-for-ts
,而是关于react-i18next
的工作方式。
在i18next
中,这会很好用:
// when you call i18next directly,
i18next.t('common:auth.login.text'); // work fine, not recommended, but what you want specifically.
i18next.t('auth.login.text', { ns: 'common' }); // work fine too.
但是,使用 react-i18next
时,您必须使用 useTranslation()
三种方法为多个翻译文件指定命名空间
>、withTranslation()
和 Translation
(如 documentation 中所述):
// when you call react-i18next methods,
const { t } = useTranslations();
t('common:auth.login.text'); // fail.
当这三个方法不带参数传递时,它会识别 i18next.ts
文档中指定的默认命名空间
。但是,每当您想在 t
函数中指定命名空间
时,最好按如下方式执行:
const { t } = useTranslation('common'); // and when you have multiple, put all of them in an array.
t('common:auth.login.text'); // would work fine.
希望以上回答对您有所帮助。
关于typescript - 将 i18next 与 TypeScript 结合使用 : How to Support Prefixed Namespace Keys in the t Function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77665321/