新聞中心
現(xiàn)在的網(wǎng)站很多時候都需要面對世界過個地區(qū)的人們訪問,如果針對每個地區(qū)的人都單獨(dú)構(gòu)建一個網(wǎng)站的話,這樣會非常費(fèi)時費(fèi)力,因此最好的解決辦法就是根據(jù)用戶的訪問來對網(wǎng)站的內(nèi)容進(jìn)行翻譯,這種翻譯一般是通過從數(shù)據(jù)庫獲取對應(yīng)的語言內(nèi)容來進(jìn)行頁面內(nèi)容的替換。

在 react 中,其實(shí)已經(jīng)有人封裝了多語言的擴(kuò)展庫,我們只需要安裝它就可以在我們的 react 項(xiàng)目中實(shí)現(xiàn)網(wǎng)站的多語言切換。
下面我們簡單介紹下如何使用它。
首先,我們需要通過包管理工具比如 npm 等來安裝它。
npm install i18next react-i18next@latest
然后,我們創(chuàng)建一個 i18n.js 配置文件,里面對多語言進(jìn)行相關(guān)的配置。
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n
.use(initReactI18next)
.init({
debug: true,
fallbackLng: 'en',
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
// language resources
resources: {
en: {
translation: {
welcome: "Welcome to React"
}
},
zh: {
translation: {
welcome: "歡迎使用 React"
}
},
}
});
export default i18n;
在這里面,resources 屬性里面配置的就是對應(yīng)的各個語言的翻譯,這里面的數(shù)據(jù),一般我們都是從數(shù)據(jù)庫中獲取,這里為了演示,我們直接寫在了配置文件中。
接下來,我們介紹下如何在項(xiàng)目中使用它。
import { useTranslation } from "react-i18next";
const lngs = [
{ code: "en", native: "English" },
{ code: "zh", native: "Chinese" },
];
export default function App() {
const { t, i18n } = useTranslation();
const handleTrans = (code) => {
i18n.changeLanguage(code);
};
return (
{t("welcome")}
{lngs.map((lng, i) => {
const { code, native } = lng;
return ;
})}
);
}
在這里,我們放置了兩個按鈕,一個是中文,一個是英文,點(diǎn)擊中文,顯示中文內(nèi)容,點(diǎn)擊英文,顯示英文內(nèi)容,這里我們主要就是通過調(diào)用i18n.changeLanguage這個函數(shù)來實(shí)現(xiàn)對應(yīng)語言的轉(zhuǎn)換,我們需要翻譯的短語使t函數(shù)進(jìn)行包裹。
對于用戶語言的識別,我們主要可以通過下面的幾種方式進(jìn)行識別。
- cookie
- localStorage
- navigator
- querystring (append ?lng=LANGUAGE to URL)
- htmlTag
- path
- subdomain
這些方式 i18next 都是支持的,不過使用的時候需要先安裝。
npm install i18next-browser-languagedetector --save
使用方式如下:
import i18n from "i18next";
import detector from "i18next-browser-languagedetector";
import { reactI18nextModule } from "react-i18next";
import translationEN from '../public/locales/en/translation.json';
import translationDE from '../public/locales/de/translation.json';
// the translations
const resources = {
en: {
translation: translationEN
},
de: {
translation: translationDE
}
};
i18n
.use(detector)
.use(reactI18nextModule) // passes i18n down to react-i18next
.init({
resources,
fallbackLng: "en", // use en if detected lng is not available
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false // react already safes from xss
}
});
export default i18n;
i18next 此外還支持熱更新,還支持 SSR,它還提供了Trans組件,可以讓你方便的集成到項(xiàng)目中。
總之,i18next 是非常不錯的多語言站點(diǎn)插件,更多的使用方法和介紹你可以參考官網(wǎng)。
網(wǎng)頁名稱:多語言站點(diǎn)React前端框架i18next
文章路徑:http://www.5511xx.com/article/cdisphj.html


咨詢
建站咨詢
