首页 > 解决方案 > 在 React 应用程序中向用户(和语言翻译)存储文本消息、说明……的最佳方式

问题描述

假设我想在我的 React 应用程序上显示消息:某个按钮上的消息“发送代码”、“引入下面的代码”等指令。

目前,我直接在按钮上显示它们,比方说:

<Button className="Log_in_button" block size="lg"  onClick={() => this.requestForValidationVerificationCode()}>
    {'Send code'}
</Button>

但是必须有一种方法可以将此消息存储在某个配置文件中以从中获取它。这种文件的结构应该是什么,我应该如何在我的 React 文件中获取消息?

此外,我确信有一种适当的方法可以将翻译存储为其他语言:西班牙语、德语、俄语……因此,如果您的用户从下拉列表中选择了该语言,您将显示相同的文本,但使用所选的语言。我应该如何引入对语言的依赖:将所有语言的文本放在同一个文件中,并通过参数(比如语言='ES')选择语言,每种语言都有不同的文件,......?

任何有关如何以类似 React 的方式正确处理此问题的帮助/指导将不胜感激。

提前致谢!

标签: reactjsreact-nativetext

解决方案


您正在关注国际化!最丰富的库之一是用于反应的i18next库!使用简单!好医生!这个答案将足以完成它!

https://react.i18next.com/

注意:(i18n => 国际化 => i <18 chars> n)!

入门是一个很好的起点!医生很好!

https://react.i18next.com/getting-started

对于简单的翻译,您可以使用如下所示的内容:

<div>{t('simpleContent')}</div>

如果没有提供翻译,则将使用传递给 t() 方法的任何内容!否则,您可以提供尽可能多的翻译文件!适用于所有语言!还有备用语言配置!

如何初始化和使用示例

import React from "react";
import ReactDOM from "react-dom";
import i18n from "i18next";
import { useTranslation, initReactI18next } from "react-i18next";

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    // the translations
    // (tip move them in a JSON file and import them,
    // or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui)
    resources: {
      en: {
        translation: {
          "Welcome to React": "Welcome to React and react-i18next"
        }
      }
    },
    lng: "en", // if you're using a language detector, do not define the lng option
    fallbackLng: "en",

    interpolation: {
      escapeValue: false
    }
  });

function App() {
  const { t } = useTranslation();

  return <h2>{t('Welcome to React')}</h2>;
}

// append app to dom
ReactDOM.render(
  <App />,
  document.getElementById("root")
);

你可以看看如何初始化!

以及如何通过翻译!在这种情况下,它们是内联的!或者直接通过!(看到最后!还有更多选择)

生产

对于生产有不同的选择!主要有react app(bundle)的翻译部分!或者在服务器端!对于网络应用程序!拥有它们服务器端可能更合适!

此页面将给出一个强有力的概述:

https://react.i18next.com/guides/quick-start

配置 i18n

import i18n from "i18next";
import { initReactI18next } from "react-i18next";

// the translations
// (tip move them in a JSON file and import them,
// or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui)
const resources = {
  en: {
    translation: {
      "Welcome to React": "Welcome to React and react-i18next"
    }
  },
  fr: {
    translation: {
      "Welcome to React": "Bienvenue à React et react-i18next"
    }
  }
};

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en", // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources
    // you can use the i18n.changeLanguage function to change the language manually: https://www.i18next.com/overview/api#changelanguage
    // if you're using a language detector, do not define the lng option

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

  export default i18n;

然后确保在 index.js (ts) 中导入它!所以初始化脚本执行!并创建 i18next 实例!

import React, { Component } from "react";
import ReactDOM from "react-dom";
import './i18n'; // <<<<<<<<--here
import App from './App';

// append app to dom
ReactDOM.render(
  <App />,
  document.getElementById("root")
);

更完整的配置和选项

https://react.i18next.com/latest/using-with-hooks

但在安装命令之前:

npm install react-i18next i18next --save

// if you'd like to detect user language and load translation
npm install i18next-http-backend i18next-browser-languagedetector --save

检查下面代码中的注释:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
// don't want to use this?
// have a look at the Quick start guide 
// for passing in lng and translations on init

i18n
  // load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
  // learn more: https://github.com/i18next/i18next-http-backend
  // want your translations to be loaded from a professional CDN? => https://github.com/locize/react-tutorial#step-2---use-the-locize-cdn
  .use(Backend)
  // detect user language
  // learn more: https://github.com/i18next/i18next-browser-languageDetector
  .use(LanguageDetector)
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    fallbackLng: 'en',
    debug: true,

    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    }
  });


export default i18n;

您可以看到有一个插件可以帮助从后端获取翻译!检查这里的链接!

一个也可以进行ajax调用!并获得 json 响应!保存准确的翻译然后加载它!您可以在最后一节中查看如何!

请务必检查评论!和文档链接!检查每个插件的作用!语言检测器!有帮助!

用法和翻译

翻译您的内容((使用))(您在按钮上方想要的内容:

useTranslation() 钩子!

import React from 'react';

// the hook
import { useTranslation } from 'react-i18next';

function MyComponent () {
  const { t, i18n } = useTranslation();
  return <h1>{t('Welcome to React')}</h1>
}

有关更多选项和详细信息,请参阅页面!使用HOC翻译组件!还有反式组件!

好吧,我将包括示例:

import React from 'react';

// the hoc
import { withTranslation } from 'react-i18next';

function MyComponent ({ t }) {
  return <h1>{t('Welcome to React')}</h1>
}

export default withTranslation()(MyComponent);
import React from 'react';

// the render prop
import { Translation } from 'react-i18next';

export default function MyComponent () {
  return (
    <Translation>
      {
        t => <h1>{t('Welcome to React')}</h1>
      }
    </Translation>
  )
}
import React from 'react';
import { Trans } from 'react-i18next';

export default function MyComponent () {
  return <Trans><H1>Welcome to React</H1></Trans>
}

// the translation in this case should be
"<0>Welcome to React</0>": "<0>Welcome to React and react-i18next</0>"

有关跨式的更多详细信息 显然更酷的方式是钩式!

否则Trans是包含 dom 元素的翻译方式(jsx)!

翻译和地点

两种选择!将它们放在服务器端!或应用程序包的一部分

服务器端

对于服务器端,您可以使用上面已经提到的插件非常简单!检查这里的链接!

或者甚至只是有一个提供翻译文件的端点!并自己加载它们!确保按需加载翻译!对于一个特定的语言!并在变化!该插件已经允许这一切!

知道动态加载翻译!您可以使用:

i18n.addResources()i18n.addResourcesBundle()

第二个可能更合适,因为它提供了深度和过度的额外选择!

https://www.i18next.com/overview/api#addresource

而且很明显!有了后端,一切都作为 json 响应!哪个会自动加载为 js 对象!

在服务器端提到!翻译好放在文件里!两个都干净!并且可以传递给没有 IT 人员来更新他们或添加新的语言翻译。

应用程序的一部分

否则另一种选择!是让他们成为应用程序的一部分!对于网络应用程序,您通常不想这样做以保持捆绑小!但是如果你在桌面应用程序上工作,比如使用电子!然后让它在本地有意义!

一个好方法是:

Generally you'll make an i18n folder 

My config would be!

[![enter image description here][2]][2]

`index.js` is thge i18n module initializing and config file! The one already listed twice!

```ts
// ....

import translationEN from './locales/en/translation.json';
import translationFR from './locales/fr/translation.json';

import detector from 'i18next-browser-languagedetector'

// the translations
const resources = {
    en: {
        translation: translationEN
    },
    fr: {
        translation: translationFR
    }
};

// ....

我在这里使用了 json 文件!并且可以让人写翻译!然后添加它们!而且更有条理!

也可以使用 js 文件而不是 json 文件!

改变语言

https://www.i18next.com/overview/api#changelanguage

导入 i18n 导出实例!

i18n.changeLanguage('fr') // return promise

i18next 库和实例!

知道这里我们使用的是 i18n 库

https://www.i18next.com/

和反应绑定!(配置中的初始化)

知道您可以使用 i18next 实例和所有它的 api!(从配置模块导入它!因为我们在那里导出它!

这是api!

https://www.i18next.com/overview/api

以防万一!一般来说,你不需要在反应时打扰!但你可以!例如动态加载资源(翻译)(不是预加载)!正如已经提到的!

定位一个gui管理工具和国际化平台

https://react.i18next.com/guides/multiple-translation-files

这里提到了!

您既可以获利又可以检查多翻译!还有命名空间!

否则对于大项目!Locize 可能看起来很有趣!

在大项目中!翻译应始终分开!

在服务器端!您总是可以将翻译放在 json 文件中!而普通人也能驾驭!就像真正的聘请翻译!


推荐阅读