【问题标题】:i18next translation inside map地图内的 i18next 翻译
【发布时间】:2021-11-25 14:20:38
【问题描述】:

我在使用 react-i18next 的地图函数中翻译有问题。

import data from '../../projectsData.json';
import { useTranslation } from 'react-i18next';

const MyComponent = () => {
    const { t } = useTranslation();

    return (
        <div>
            {data.projects.map((project, index) => {
                return (
                    <Link to='/' key={index}>
                        <img
                            src={project.image}
                            alt={project.title}
                        />
                        <p>{project.title}</p>    //there should be translated text
                    </Link>
                );
            })}
        </div>
    );
};

projectsData.json 文件如下所示:

{
    "projects": [
        {
            "title": "projekt 1",
            "description": "to jest opis projektu 1",
            "id": "111",
            "image": "https://placedog.net/640/480/1"
        },
        {
            "title": "projekt 2",
            "description": "to jest opis projektu 2",
            "id": "222",
            "image": "https://placedog.net/640/480/2"
        },
        {
            "title": "projekt 3",
            "description": "to jest opis projektu 3",
            "id": "333",
            "image": "https://placedog.net/640/480/3"
        },
        {
            "title": "projekt 4",
            "description": "to jest opis projektu 4",
            "id": "444",
            "image": "https://placedog.net/640/480/4"
        }
    ]
}

我还需要将翻译添加到翻译文件中,但这将是一个带有项目标题的对象:

{    "projects": {
        "title1": "Project 1",
        "title2": "Project 2",
        "title3": "Project 3",
        "title4": "Project 4"
    }
}

所以我无法转动它:

"title": "projekt 1"

进入:

"title": `${t('projects.title1')}

在 projectsData.json 文件中,因为它是 json。 我也只能在 React 组件中使用 useTranslation 钩子。我该如何处理这个问题?

【问题讨论】:

    标签: reactjs i18next react-i18next


    【解决方案1】:

    要在反应组件外使用翻译,您可以使用i18next.t

    
    import i18next from 'i18next';
    i18next.t('your word');
    
    

    您也不需要更改 json 文件。你可以使用t方法翻译成地图功能

    
    <p>{t(project.title)}</p>
    
    

    【讨论】:

    • 没错。但在翻译文件中,我无法设置多个相同的键('title',在项目对象内)。所以我仍然需要:选项1:在projectData.json文件中使用i18中的t()函数,我猜这是不可能的或选项2:以某种方式从段落内的翻译JSON映射项目对象,但它在map函数内.. . 我错了吗?
    • 我认为您需要 i18next 中的插值之类的东西,您可以通过以下链接进行检查:i18next.com/translation-function/interpolation
    猜你喜欢
    • 1970-01-01
    • 2012-10-27
    • 2015-11-04
    • 1970-01-01
    • 2021-06-26
    • 2020-11-24
    • 2021-08-14
    • 2015-12-27
    • 1970-01-01
    相关资源
    最近更新 更多