【问题标题】:React + i18next: Why aren't my nested keys working?React + i18next:为什么我的嵌套键不起作用?
【发布时间】:2019-08-28 11:43:44
【问题描述】:

我正在为一个小型网站使用 ReactJS。我决定使用 i18next 进行国际化,它可以工作 - 除非我使用嵌套引用作为翻译键。

在以下示例中,显示了 intro1 和 intro2 键,但未找到 welcome.headtitle(控制台中出现错误“missingKey”)。

App.js:

...
 <p><Trans i18nKey='intro1'/></p>
 <p><Trans i18nKey='intro2'/></p>
 <p><Trans i18nKey='welcome.headtitle'/></p>
...

translation.json:

{
"welcome": {
    "headtitle": ...
    ...
  },
  "intro1": ...,
  "intro2": ...,
}

我知道 i18next 允许嵌套 JSON 翻译对象。我究竟做错了什么?我检查了文档和示例,没有发现任何错误。

【问题讨论】:

  • 你能发布你的 i18n 初始化代码吗?

标签: reactjs react-i18next


【解决方案1】:

虽然使用“welcome.name”等的答案是有效的用法,但对于我的用例,我实际上需要使用结构化键,以便更好地构建我的翻译。

嵌套值对我有用的原因是从 i18n.init 函数中删除了 keySeparator: false。

代码是:


i18n.use(initReactI18next).init({
  resources: {
    en: {translation: EN},
    fr: {translation: FR},
  },
  lng: 'en',
  fallbackLng: 'en',
  // keySeparator: false, // this was the line that I've had to remove to make it work
  interpolation: {
    escapeValue: false,
  },
});

我的 JSON 看起来像:

{
  "nested": {
    "value": "Trying a nested value"
  }
}

我的 HTML(我的反应组件中的 div):

<div>{t("nested.value")}</div>

【讨论】:

  • 仅供参考,如果您想重新启用嵌套键,请不要使用 keySeparator: true。您需要像这样指定键分隔符:keySeparator: '.'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
  • 2020-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多