我在我的项目中使用
i18next
和 react-18next
。当使用 useTranslation
中的 react-i18next
时,我们有一个很好的选项“keyPrefix”来帮助我们减少代码重复。但有时我需要在组件之外使用 i18next,所以我想知道它是否有像 useTranslation
这样的抽象可以让我使用 ns
或 keyPrefix
而不必每次使用 t
函数时都重复它?
我尝试查看 i18next 的文档,但我找不到任何东西(还?)。
我尝试使用适配器模式自己完成此操作,但打字稿支持会中断,因为我无法获取
t
函数的键的类型。
在
i18next
中这样做甚至更容易。我只想使用 react-i18next
的 documentation 作为示例:
// having JSON in namespace "translation" like this:
/*{
"very": {
"deeply": {
"nested": {
"key": "here"
}
}
}
}*/
const { t } = useTranslation('translation', { keyPrefix: 'very.deeply.nested' });
const text = t('key'); // "here"
并且在
i18next
中(如其文档中所述):
// for different namespaces than default one
i18next.t('translation:very.deeply.nested.key');
// it is recommended to use the ns option:
i18next.t('very.deeply.nested.key', { ns: 'translation'});
如果您需要在某些特定的 JavaScript 文件中将其设置为默认值,请检查:
i18next.getFixedT(lng, ns, keyPrefix)
。
希望这个答案有帮助