react项目使用i18n进行国际化封装


react项目使用i18n进行国际化封装

  1. 安装

    npm i i18next react-i18next --save
    
  2. 配置i18n:

    • 在根目录新建一个目录i18n
    • i18n目录添加en.jsonzh.json
    {
      "footer": { "detail" : "版权所有 @ React 旅游网" }
    }
    
    {
      "footer": { "detail" : "All rights reserved @ ReactTravel.com" }
    }
    
    • i18n目录新建文件index.ts
    import i18n from 'i18next'
    import {initReactI18next} from 'react-i18next'
    
    import enTranslation from './en.json'
    import zhTranslation from './zh.json'
    
    const lng = 'zh'
    
    i18n.use(initReactI18next)
      .init({
        resources: {
          en: {translation: enTranslation},
          zh: {translation: zhTranslation}
        },
        lng,
        fallbackLng: lng,
        interpolation: {escapeValue: false}
      })
    
    export default i18n
    
  3. 在根目录的index.tsx中引入i18n/index.ts

    import React from 'react'
    import ReactDOM from 'react-dom'
    import 'antd/dist/antd.css'
    import './index.css'
    import App from './App'
    import 'i18n'
    
    ReactDOM.render(
      
        
      ,
      document.getElementById('root')
    )
    
  4. 在组件中使用i18n

    • class类组件
    import {Component} from "react";
    import { withTranslation, WithTranslation } from 'react-i18next'
    
     class FooterComponent extends Component {
      render() {
        const { t } = this.props
        return (
    {/!*版权所有 @ React 旅游网*!/} {t('footer.detail')}
    ); } } export const Footer = withTranslation()(FooterComponent)
    • 函数式组件
    import {FC} from "react";
    import {useTranslation} from 'react-i18next'
    
    export const Footer: FC = () => {
      const {t} = useTranslation()
      return (
    {/!*版权所有 @ React 旅游网*!/} {t('footer.detail')}
    ) }