通过reactjs i18next翻译对每种语言使用多个Json文件

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

我的reactjs项目中有一个名为“en.json”的json文件,以便使用i18next翻译:

"Ascending": "Ascending",
"Descending": "Descending",
"All": "All",
"job-types": {
        "remote": "remote",
        "temporary": "temporary",
        "fulltime": "fulltime",
        "parttime": "parttime"
     },  
 ...
   }

我想在另一个 json 文件中插入“job-types”项目,然后在我当前的“en.json”文件中引用它。是否可以使用嵌套的 json 文件或者有什么方法可以解决这个问题?如果有,请问如何?

在 i18n.js 文件中我有:

  const resources = {
    en: {
      translation: translationEN
    },
    fa: {
      translation: translationFA
    },
    ar: {
      translation: translationAR
    }
  };
  
  i18n
    .use(Backend)
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
      resources,
      fallbackLng: 'en',
      debug: true,
      interpolation: {
        escapeValue: false, // not needed for react as it escapes by default
      }
    });

 export default i18n;

translationEN、translationFA 和 TranslationAR 是所需语言(英语、波斯语或波斯语和阿拉伯语)的导入 .json 文件(到 i18n.js)。

reactjs json nested
2个回答
0
投票

为了引用 JSON 文件中的键,您首先需要使用

JSON.parse()
,以便可以遍历该对象。

const myResponse = JSON.parse(response);
const jobTypes = myResponse['job-types'] // dashed keys must be accessed through an index

如果您需要访问该文件,请链接到它:

const myResponse = await fetch('path/to/file.json');
const jsonBody = await myResponse.json();
otherObject.jobTypes = jsonBody['job-types'];

JSON 不支持链接到其他文件,因为它只是文本。您可以将文件的位置作为值发送,但这是您可以获得的最远位置。

希望这有帮助。


0
投票

最后,为了使用翻译json文件而不那么复杂,我为每种语言使用了两个或多个.json文件并将它们连接起来,而不是通过以下方式嵌套它们:

const resources = {
    en: {
      translation: { ...translationEN, ...translationEN1}
    },
    fa: {
      translation: { ...translationFA, ...translationFA1}
    },
    ar: {
      translation: { ...translationAR, ...translationAR1}
    }
  };
  
  i18n
    .use(Backend)
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
      resources,
      fallbackLng: 'en',
      debug: true,
      interpolation: {
        escapeValue: false, // not needed for react as it escapes by default
      }
    });

 export default i18n;

第一个json文件:

{
   "Ascending": "Ascending",
   "Descending": "Descending",
   "All": "All", 
   ...
 }

和其他 json 文件:

 {
    "job-types": {
        "remote": "remote",
        "temporary": "temporary",
        "fulltime": "fulltime",
        "parttime": "parttime"
    }
 }
© www.soinside.com 2019 - 2024. All rights reserved.