【问题标题】:How mapping with .map a .json file using translation with i18next in React.js?如何使用 React.js 中的 i18next 翻译与 .map 映射 .json 文件?
【发布时间】:2021-05-08 20:01:38
【问题描述】:

大家好,我有一个问题要问你。实际上,我想使用 .json 中的文本并使用基于用户语言或检测到的语言的翻译来映射和呈现组件。

这就是translation.json(其他语言也一样)

{ "myText":[
          { "id":1,
            "text":"my text"
          },
          {
            "id":2,
            "text":"my text"
          }
  ]
}

现在我想映射这个 .json 并根据我的组件中的语言返回文本。如果我这样做:

import { withNamespaces } from 'react-i18next';
import data from '../locales/en/translation.json';

function Component({t}) {
  return (
    <>
      {data.myText.map((item) => (
        <div key={t(item.id)}>
          {t(item.text)}
        <div/>       
    ))}          
    </>
  )
}

export default withNamespaces()(Component)

这仅返回“en”翻译,因为导入基于此 .json 文件。现在如何通过 .map 进行基于用户语言的翻译?

【问题讨论】:

标签: arrays json reactjs jsx array.prototype.map


【解决方案1】:

好的,我使用了:

{i18next.t('myText', { returnObjects: true }).map((item) => (
    <div key={t(item.id)}>
      {t(item.text)}
    </div>
))}

解决方案在这里:https://www.i18next.com/translation-function/objects-and-arrays#arrays

【讨论】:

    猜你喜欢
    • 2019-03-03
    • 2021-09-24
    • 2016-04-24
    • 2020-08-31
    • 2014-07-27
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    相关资源
    最近更新 更多