如何在React项目中基于i18next实现全局多语言切换?
React项目集成i18next实现英法语全局切换(含API动态文本翻译)
一、安装依赖
npm install react-i18next i18next i18next-http-backend i18next-browser-languagedetector # 或使用yarn yarn add react-i18next i18next i18next-http-backend i18next-browser-languagedetector
二、初始化i18n配置
在src目录新建i18n.js文件:
import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import Backend from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) .init({ fallbackLng: 'en', debug: false, interpolation: { escapeValue: false, }, supportedLngs: ['en', 'fr'], backend: { loadPath: '/locales/{{lng}}/translation.json', }, }); export default i18n;
创建翻译文件
在public目录下新建locales文件夹,分别创建英法语翻译文件:
public/locales/en/translation.json
{ "header": { "main": "Main", "aboutUs": "About us", "management": "Management", "news": "News", "contacts": "Contacts", "vacancies": "Vacancies", "services": "Services", "english": "English", "french": "French" }, "history": { "title": "About us" } }
public/locales/fr/translation.json
{ "header": { "main": "Accueil", "aboutUs": "À propos de nous", "management": "Gestion", "news": "Nouvelles", "contacts": "Contacts", "vacancies": "Offres d'emploi", "services": "Services", "english": "Anglais", "french": "Français" }, "history": { "title": "À propos de nous" } }
三、修改Header组件实现语言切换
import React, { useState } from "react"; import styled from "./style.module.css"; import Logo from "./photo/logo.svg"; import { IoLogoWhatsapp } from "react-icons/io"; import { SiTelegram } from "react-icons/si"; import { AiOutlineMenu, AiOutlineClose } from "react-icons/ai"; import { Link } from "react-router-dom"; import { useTranslation } from 'react-i18next'; export default function Header() { const [nav, setNav] = useState(false); const { t, i18n } = useTranslation(); const changeLanguage = (lng) => { i18n.changeLanguage(lng); }; return ( <div className={styled.header}> <div className={styled.header__container}> <div className={styled.header__info}> <div className={styled.header__media}> <IoLogoWhatsapp size={30} /> <SiTelegram size={30} /> <p className={styled.header__phone}>+996702521200</p> </div> <div className={styled.header__buttons}> <button className={styled.header__lang} onClick={() => changeLanguage('en')} > {t('header.english')} </button> <button className={styled.header__lang} onClick={() => changeLanguage('fr')} > {t('header.french')} </button> </div> </div> <div className={styled.header__line}></div> <div className={styled.header__pages}> <div className={styled.header__logo}> <img src={Logo} className={styled.header__image} /> <h1 className={styled.header__title}>{t('header.main')}</h1> </div> <div className={styled.header__chapters}> <ul className={ nav ? [styled.header__parts, styled.active].join(" ") : [styled.header__parts] } > <Link to="/main" style={{ textDecoration: "none" }}> <li>{t('header.main')}</li> </Link> <Link to="/history" style={{ textDecoration: "none" }}> <li>{t('header.aboutUs')}</li> </Link> <Link to="/management" style={{ textDecoration: "none" }}> <li>{t('header.management')}</li> </Link> <Link to="/news" style={{ textDecoration: "none" }}> <li>{t('header.news')}</li> </Link> <Link to="/contacts" style={{ textDecoration: "none" }}> <li>{t('header.contacts')}</li> </Link> <Link to="/vacancies" style={{ textDecoration: "none" }}> <li>{t('header.vacancies')}</li> </Link> <Link to="/services" style={{ textDecoration: "none" }}> <li>{t('header.services')}</li> </Link> </ul> <div onClick={() => setNav(!nav)} className={styled.mobile_btn}> {nav ? <AiOutlineClose size={30} /> : <AiOutlineMenu size={30} />} </div> </div> </div> </div> </div> ); }
四、修改History组件处理API动态文本翻译
情况1:API返回多语言字段(如text_en、text_fr)
import React, { useState, useEffect } from "react"; import styled from "./style.module.css"; import axios from "axios"; import { useTranslation } from 'react-i18next'; export default function History() { const [data, setData] = useState({}); const token = "Fb79eACvxFjhn3afD7h7Akoi0MiofDFm"; const { i18n } = useTranslation(); const currentLng = i18n.language; useEffect(() => { const fetchData = async () => { try { const response = await axios.get( `http://130.61.61.186:8055/items/History`, { headers: { Authorization: `Bearer ${token}` } } ); setData(response.data.data); } catch (error) { console.log(error); } }; fetchData(); }, []); const getTranslatedText = () => { return data ? (currentLng === 'fr' ? data.text_fr : data.text_en) : ''; }; return ( <div> <div className={styled.container}> <h1 className={styled.title}>{t('history.title')}</h1> <div className={styled.text}> <p>{getTranslatedText()}</p> </div> </div> </div> ); }
情况2:API支持传入语言参数返回对应文本
import React, { useState, useEffect } from "react"; import styled from "./style.module.css"; import axios from "axios"; import { useTranslation } from 'react-i18next'; export default function History() { const [data, setData] = useState({}); const token = "Fb79eACvxFjhn3afD7h7Akoi0MiofDFm"; const { t, i18n } = useTranslation(); useEffect(() => { const fetchData = async () => { try { const response = await axios.get( `http://130.61.61.186:8055/items/History`, { headers: { Authorization: `Bearer ${token}` }, params: { locale: i18n.language } } ); setData(response.data.data); } catch (error) { console.log(error); } }; fetchData(); }, [i18n.language]); return ( <div> <div className={styled.container}> <h1 className={styled.title}>{t('history.title')}</h1> <div className={styled.text}> <p>{data.text || ''}</p> </div> </div> </div> ); }
五、全局引入i18n配置
在项目入口文件(如src/index.js)顶部添加:
import './i18n';
内容的提问来源于stack exchange,提问作者Bale
相关产品推荐
相关产品推荐

