reactjs - 如何在 react-i18next 运行时加载翻译文件
问题描述
我正在使用 react-i18next 作为我的国际化库选择构建一个反应应用程序。虽然我可以将我的翻译文件分成多个文件并在我的应用程序中使用它们,但我担心随着时间的推移这些翻译可能会增长,并且在构建时加载它们是一种低效的方法。它在他们的文档中说您可以手动加载翻译文件,但他们并没有有效地指导您如何这样做。
目前我的代码是:
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;
组件.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"
}
登陆.json
{
"title": "Landing Page",
"Privacy": "Privacy and Personalization"
}
我想在组件渲染而不是应用程序构建上加载我的翻译文件,我该怎么做?在前端处理翻译语言时涉及的最佳实践是什么?从后端加载语言是否更有效,如果是,如何在运行时加载语言?
解决方案
使用该ns
参数告诉 i18next 在您的应用加载时默认加载哪些命名空间。如果你想在运行时加载不同的命名空间,文档说你可以调用i18next.loadNamespaces('anotherNamespace', (err, t) => { /* ... */ });
.
如果您担心巨大的 JSON 文件和可扩展性,您可能需要查看i18nexus.com以管理翻译。用于管理 i18next 翻译文件的超酷平台,您甚至可以使用 Google 翻译实现自动化。
推荐阅读
- callback - google oauth回调多次附加参数
- r - 使用神经元网络进行分类
- ms-access - 连接多个字符串同时忽略空值
- android - RecyclerView 不断调用 LoadMore 分页
- python - 如何使用模拟进行猴子补丁并设置返回值
- verilog - MIG MCB 意外写入行为
- ios - UITabbarController 隐藏标签栏破坏了安全区域布局
- node.js - 如何将 Twilio 节点与 TypeScript 一起使用?
- php - 未捕获的 ArgumentCountError:函数 wpdb::prepare():update 的参数太少
- c# - NetSuite C# 控制台应用程序 Web 服务令牌身份验证返回“模糊身份验证”