本文介绍了如何使用react-i18next使用.map()转换对象数组中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
刚开始使用i18next时,在转换以下数据时会遇到一些问题.
Just started using i18next and having a bit of issues translating the following data.
export const educationData = [
{ education: "Some education 1", timeframe: "2017 - 2018", id: 1 },
{ education: "Some education 2", timeframe: "2016 - 2017", id: 2 },
{ education: "Some education 3", timeframe: "2015 - 2016", id: 3 },
{ education: "Some education 4", timeframe: "2014 - 2015", id: 4 }
];
针对不同语言的语言环境中的JSON如下:
JSON in locales for different languages looks like:
"education": {
"heading": "Education",
"educationData": [
{
"id": 1,
"education": "Some education 1",
"timeframe": "2017 - 2018"
},
{
"id": 2,
"education": "Some education 2",
"timeframe": "2016 - 2017"
},
{
"id": 3,
"education": "Some education 3",
"timeframe": "2015 - 2016"
},
{
"id": 4,
"education": "Some education 4",
"timeframe": "2014 - 2015"
}
]
}
组件外观如下:
import React from "react";
import { useTranslation } from "react-i18next";
import { educationData } from "../data/educationData";
import Education from "./Education.js";
function ListEducation() {
const { t } = useTranslation();
return (
<div className="education py-1">
<h2>{t("education.heading")}</h2>
<hr />
{educationData.map((edu) => (
<Education
key={edu.id}
education={edu.education}
timeframe={edu.timeframe}
/>
))}
</div>
);
}
export default ListEducation;
如何在.map()函数中使用翻译?在.map()之外,像t("education.educationData.0.education")之类的东西可以正常工作.
How do i get the translations to work in the .map() function? Outside of .map() something like t("education.educationData.0.education") works fine.
在.map函数内部,它仅将"education.educationData.0.education"输出为字符串.
Inside .map function it just outputs "education.educationData.0.education" as a string.
推荐答案
您可以尝试
{t(`education.educationData.${id}.${education}`)}
您基本上是在串联字符串.
You're basically concatenating the string.
这篇关于如何使用react-i18next使用.map()转换对象数组中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!