React + i18next:为什么我的嵌套键不起作用?

时间:2019-08-28 11:43:44

标签: reactjs react-i18next

我在一个小型网站上使用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转换对象。我究竟做错了什么?我检查了文档和示例,没有发现任何错误。

2 个答案:

答案 0 :(得分:20)

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

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

代码为:


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(我的react组件中的div):

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

答案 1 :(得分:0)

代替这个

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

使用此

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