react-intl 国际化使用方法

781 阅读1分钟

这篇掘金主要写的就是react国际化的用法,这是我自己的思路可能有些不清晰,希望大家点评一下。

使用方法

首先我们需要先在react中安装 react-intl

创建语言包

然后我们需要有一个语言包,我写了一个简单的标签的国际化进行中英文切换

英文的语言包

//英文
module.exports = {
    article: "article",
    archive: "archive",
    knowledge: "knowledge",
    leave: "leave",
    about: "about"
}

中文的语言包

//中文
module.exports = {
    article: "文章",
    archive: "归档",
    knowledge: "知识小册",
    leave: "留言",
    about: "关于"
}

将文件包抛出之后我们需要创建一个IntlProvid.ts文件 创建这个文件就相当于reducer用来判断我们需要返回的是中文还是英文,然后引入react-intl中的 IntlProvider 用来实现我们的国际化

创建IntlProvid.ts

// 国际化
import React, { FC } from 'react';
import { IntlProvider } from 'react-intl';
import zh from './zh'
import en from './en'
import { fillObj } from './fillobj'
interface Myprops {
    locale: string,
}
const IntlProvid: FC<Myprops> = ({ children, locale }) => {
    {/* 判断仓库中是 中文还是英文传入对应的 语言包 */ }
    let language = (type: string) => {
        switch (type) {
            case "en":
                return en
            case "zh":
                return zh
            default:
                return zh
        }
    }
    return (
        <div>
            <IntlProvider locale={locale} messages={fillObj(language(locale))}>
                {children}
            </IntlProvider>
        </div>
    );
};





export default IntlProvid

然后在index.ts中引入我们的国际化IntlProvid.ts文件,将IntlProvid套在render中的最外层,实现一个灌入的效果,

将IntlProvid灌入app

import IntlProvid from "./locales/IntlProvid"
let vales = localStorage.getItem("lng")
ReactDOM.render(
  <Provider store={store}>
    <IntlProvid locale={vales as string}>
    <App />
    </IntlProvid>
  </Provider>,
  document.getElementById('root')
);

之后在我们的router-view渲染的页面将react-intl中的FormattedMessage引入进来 再将我们的key放到FormattedMessage中,通过我们的key来给对应的数据进行中英文切换,因为我的路由表用的是id,所以我引入的id就充当我们的key,以免发生冲突

{
  navlink && navlink.length > 0 ? navlink.map((item, index) => {

      return <NavLink key={index} to={item.path as string} >
          <FormattedMessage id={item.id} />
      </NavLink>

  }) : null
}

实现效果

中文

image.png

英文

image.png