简体   繁体   English

React i18n 语言 object 映射

[英]React i18n language object mapping

How do I iterate through the menu object items with react i18n?如何使用 react i18n 遍历menu object 项? Here is an extract from the translation.json file: The desired outcome is to use .map(items) loop to output translations with <ul><li></li></ul>这是translation.json文件的摘录: 期望的结果是使用.map(items)循环到 output 翻译<ul><li></li></ul>

{
  "lang": "lv",
  "menu": {
    "index": "galvene",
    "food_menu": "menu",
    "about_us": "par mums",
    "delivery": "piegāde"
  }
}

App component, I wish to get the output in:应用程序组件,我希望在以下位置获取 output:

function App() {
    const { t, i18n } = useTranslation();
    const changeLanguage = (language) => {
        i18n.changeLanguage(language)
    };

  return (
      <div>
          /* The output should be here */
      </div>
  );
}

You can import the JSON file and then iterate the keys.您可以导入 JSON 文件,然后迭代密钥。

import translations from "./translation.json";


function App() {
    const { t, i18n } = useTranslation();
    const changeLanguage = (language) => {
        i18n.changeLanguage(language)
    };

  return (
      <div>
          <ul>
            {Object.keys(translations.menu).map((key) => (
              <li>{t(key)}</li>
            ))}
          </ul>
      </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM