i18next 有 keyPrefix 选项吗?

问题描述 投票:0回答:1

我在我的项目中使用

i18next
react-18next
。当使用
useTranslation
中的
react-i18next
时,我们有一个很好的选项“keyPrefix”来帮助我们减少代码重复。但有时我需要在组件之外使用 i18next,所以我想知道它是否有像
useTranslation
这样的抽象可以让我使用
ns
keyPrefix
而不必每次使用
t
函数时都重复它?

我尝试查看 i18next 的文档,但我找不到任何东西(还?)。

我尝试使用适配器模式自己完成此操作,但打字稿支持会中断,因为我无法获取

t
函数的键的类型。

typescript i18next react-i18next
1个回答
0
投票

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)

希望这个答案有帮助

© www.soinside.com 2019 - 2024. All rights reserved.