最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • 前端国际化, React 项目多语言:React-i18next 本地化数据 && 请求后台数据

    正文概述 掘金(果冻丨小布丁)   2021-02-02   845

    关键词:前端,国际化,多语言,react,react-i18next,i18n, antd

    GitHub Examples

    一、搭建 React 项目

    npx create-react-app demo
    cd demo
    

    二、安装 react-i18next

    npm install i18next react-i18next --save
    

    三、两种使用方式 (本地化数据、请求后台数据)

    方式一:本地化数据

    Basic sample:

    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)
        resources: {
          en: {
            translation: {
              'Welcome to React': 'Welcome to React and react-i18next'
            }
          },
          zh: {
            translation: {
              'Welcome to React': '欢迎使用 React 和 react-i18next'
            }
          }
        },
        lng: 'en',
        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'));
    

    Basic sample with JSON:

    根据 resources 上面的注释,把 resources 部分提取到 json 文件中,然后 import 引入。 en.json:

    {
      "translation": {
        "Welcome to React": "Welcome to React and react-i18next"
      }
    }
    

    zh.json:

    {
      "translation": {
        "Welcome to React": "欢迎使用 React 和 react-i18next"
      }
    }
    

    注意:translation 是 react-i18next 默认的命名空间(暂时先记着这样写,后面可以自定义命名空间)

    引入 JSON 文件:( 引入路径要根据 json 文件所在 src 目录下的相对路径 )

    import React from 'react';
    import ReactDOM from 'react-dom';
    import i18n from 'i18next';
    import en from './en.json';
    import zh from './zh.json';
    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)
        resources: {
          en,
          zh
        },
        lng: 'en',
        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'));
    

    目前为止,还没有用到 i18next-xhr-backend , 这个插件可以使你的 json 文件放到 public 目录下使用(下例 Locales JSON)。

    而 i18next-browser-languagedetector , 可以帮助你自动识别浏览器语言


    Basic sample with Locales JSON: (推荐)

    继续安装插件:

    npm install i18next-xhr-backend i18next-browser-languagedetector --save
    

    在 public 目录下新建 locales 文件夹,继续新建对应语言的文件夹 (例如:en,zh),然后创建 translation.json

    例:public/locales/en/translation.json:

    {
      "Welcome to React": "Welcome to React and react-i18next"
    }
    

    修改 i18n 初始化:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import i18n from 'i18next';
    import Backend from 'i18next-xhr-backend';
    import LanguageDetector from 'i18next-browser-languagedetector';
    import { useTranslation, initReactI18next } from 'react-i18next';
    
    i18n
      // load translation using xhr -> see /public/locales
      // learn more: https://github.com/i18next/i18next-xhr-backend
      .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
        }
      });
    
    function App() {
      const { t } = useTranslation();
    
      return <h2>{t('Welcome to React')}</h2>;
    }
    
    // append app to dom
    ReactDOM.render(<App />, document.getElementById('root'));
    

    方式二:请求后台数据

    Basic sample with XHR JSON:

    继续安装插件:

    npm install i18next-xhr-backend i18next-browser-languagedetector i18next-multiload-backend-adapter --save
    

    使用实例:

    import React, { Suspense } from 'react';
    import ReactDOM from 'react-dom';
    import i18n from 'i18next';
    import XHR from 'i18next-xhr-backend';
    import BackendAdapter from 'i18next-multiload-backend-adapter';
    import LanguageDetector from 'i18next-browser-languagedetector';
    import { useTranslation, initReactI18next } from 'react-i18next';
    
    i18n
      // learn more: https://github.com/i18next/i18next-multiload-backend-adapter
      .use(BackendAdapter)
      // 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({
        lng: navigator.language,
        fallbackLng: 'en',
        debug: true,
        preload: navigator.languages,
        interpolation: {
          escapeValue: false // not needed for react as it escapes by default
        },
        backend: {
          backend: XHR,
          allowMultiLoading: true,
          // learn more: https://github.com/i18next/i18next-xhr-backend
          backendOption: {
            loadPath: function (lngs, namespaces) {
              console.log(lngs, namespaces);
              return 'https://my-json-server.typicode.com/TserHub/Json/qinwm?lng={{lng}}&ns={{ns}}';
            },
            addPath:
              'https://my-json-server.typicode.com/TserHub/Json/qinwm?lng={{lng}}&ns={{ns}}'
          }
        }
      });
    
    function App() {
      const { t } = useTranslation();
    
      return <h2>{t('Welcome to React')}</h2>;
    }
    
    // loading component for suspense fallback
    function Loader() {
      return <div>Loading...</div>;
    }
    
    // append app to dom
    ReactDOM.render(
      <Suspense fallback={<Loader />}>
        <App />
      </Suspense>,
      document.getElementById('root')
    );
    

    更多 i18n 的详细配置 和 使用方法,请自行去参考资料查找。


    起源地下载网 » 前端国际化, React 项目多语言:React-i18next 本地化数据 && 请求后台数据

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元