如何解决如何在React-i18next中的运行时加载翻译文件
我正在构建一个带有react-i18next作为我的国际化库选择的react应用程序。尽管我可以将翻译文件分为多个文件并在应用程序中使用它们,但我担心随着时间的流逝,这些翻译可能会增长,并将其加载到内置文件中是一种低效的方法。它在他们的文档中说您可以手动加载翻译文件,但是它们并不能有效地指导您如何进行。
目前,我的代码是:
18n.js
import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
import { commonEN,landingEN } from "./locales/en";
import { commonJP,landingJP } from "./locales/jp";
const resources = {
en: {
common: commonEN,landing: landingEN,},jp: {
common: commonJP,landing: landingJP
}
};
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources,fallbackLng: "en",debug: true,ns: ["common"],defaultNS: "common",interpolation: {
escapeValue: false,});
export default i18n;
Component.js
import React from 'react'
import "./App.css";
import { Suspense } from "react";
import { useTranslation } from "react-i18next";
function Component() {
const { t,i18n } = useTranslation();
return (
<div>
<h1>{t("Account")}</h1>
<h2>{t("landing:title")}</h2>
</div>
);
}
export default Component;
common.json
{
"Account": "Account Name"
}
landing.json
{
"title": "Landing Page","Privacy": "Privacy and Personalization"
}
我想在组件渲染而不是在应用程序构建上加载我的翻译文件,我该怎么做?在前端处理翻译语言时涉及的最佳实践是什么?从后端加载语言是否更有效?如果是,如何在运行时加载语言?
解决方法
使用ns
参数告诉i18next应用程序加载时默认加载哪些名称空间。如果您想在运行时加载不同的名称空间,文档会说您可以调用i18next.loadNamespaces('anotherNamespace',(err,t) => { /* ... */ });
。
如果您担心庞大的JSON文件和可伸缩性,则可能要签出i18nexus.com来管理翻译。超级酷的平台,用于管理i18next翻译文件,您甚至可以使用Google Translate实现自动化。
,试试这个视频显示的方式.. Localise React Applications Using I18Next
我也在尝试使用您发布的有问题的方法。似乎不是一个好的选择。所以切换到使用 i18next '后端'。只需将文件保存在公共文件夹中,它们将在需要时获取。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。