重點:
動態切換語言,不刷新頁面的情況下切換,無需redux(從官網文檔找到):
選擇插件 react-i18next,
先安裝npm install i18next react-i18next --save
然后引入依賴代碼如下,
import React from 'react'; import ReactDOM from 'react-dom'; import i18n from 'i18next'; import { useTranslation, initReactI18next } from 'react-i18next';
import langCN from './langCN.js'
import langEN from './langEN.js'
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: langEN }, zh: { translation: langCN } }, lng: 'en', fallbackLng: 'en', interpolation: { escapeValue: false } });
function App() { const { t } = useTranslation(); React.translate = t; return ( <Provider store={store}> <HashRouter> <LocaleProvider locale={zhCN}> <Main /> </LocaleProvider> </HashRouter> </Provider > ); } ReactDOM.render( <App /> , document.getElementById('app') );
注意:useTranslation()必須是函數組件中使用否則會報,hooks錯誤。
React.translate = t; 將該方法放到全局函數中。

<div className={styles.savingText}>{React.translate('year')}</div>
使用全局定義的方法即可進行轉換。
目前為止,還沒有用到 i18next-xhr-backend , 這個插件可以使你的 json 文件放到 public 目錄下使用(下例 Locales JSON)。
而 i18next-browser-languagedetector , 可以幫助你自動識別瀏覽器語言
cnpm install i18next-xhr-backend i18next-browser-languagedetector --save
方式二:請求后台數據
Basic sample with XHR JSON:
cnpm install i18next-xhr-backend i18next-browser-languagedetector i18next-multiload-backend-adapter --save
i18n .use(BackendAdapter) // detect user language .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, 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}}' } } });
轉載自:https://www.cnblogs.com/jserhub/p/12651376.html