React-intl usage record

Use react-intl to implement React component internationalization

First, first install react-intl in the project:

npm install react-intl --save

二、然后在项目最外层的app.jsx文件中添加以下内容:

// 多语言
import {ConfigProvider, message} from 'antd';
import {IntlProvider, addLocaleData} from 'react-intl';
import messages from './lang/index.js';

/*
*引入与navigator.languages[0]所对应的语言;
*如果没有引入对应的语言,会使用默认的“en”;
*导致FormattedMessage的映射不会成功;
*/
import zh from 'react-intl/locale-data/zh';
import en from 'react-intl/locale-data/en';

addLocaleData([...zh, ...en]);

// currentLang是全局变量,本项目中如下定义
// const currentLang = localStorage.getItem('et_lang') || 'zh-CN';

// ConfigProvider组件是配置antd组件使用多语言的
// IntlProvider组件包裹需要实现国际化的根组件,这个组件树之后就会在配置的i18n上下文中了。
render() {
    return (
      <ConfigProvider locale={messages[currentLang].antdLocal}>
        <IntlProvider locale={currentLang} messages={messages[currentLang].local}>
          <BrowserRouter>
            <Layout/>
          </BrowserRouter>
        </IntlProvider>
      </ConfigProvider>
    )
}

Third, the configuration of the message file:

import zh_CN from './zh_CN'
import zh_MO from './zh_MO'
import en_US from './en_US'
import antdEN from 'antd/lib/locale-provider/en_US'
import antdTW from 'antd/lib/locale-provider/zh_TW'

const messages = {
  'zh-CN': {
    local: zh_CN,
    antdLocal: null
  },
  'zh-MO': {
    local: zh_MO,
    antdLocal: antdTW
  },
  'en-US': {
    local: en_US,
    antdLocal: antdEN
  },
};

export default messages;

4. In the zh_CN file, you can write the multi-language required in your project:

// zh_CN 文件
const zh_CN = {
  'noData': '无数据'
}
export default zh_CN

// zh_MO 文件
const zh_MO = { 
  'noData': '無數據'
}
export default zh_MO 

// en_US 文件
const en_US = {
  'noData': 'No data.'
}
export default en_US 

Fifth, you can then use multiple languages ​​in your own components:

import {injectIntl} from 'react-intl';

render() {
    const {intl} = this.props;
    return (
        <div>
         {intl.formatMessage({id: 'noData'})}
        </div>
    )
}

export default injectIntl(MyComp)

Six, the main function of switching the current language type:

handleLang = (e) => {
    if (e.key !== currentLang) {
      window.location.reload();
      localStorage.setItem('et_lang', e.key);
    }
};

 

Published 35 original articles · won praise 1 · views 6718

Guess you like

Origin blog.csdn.net/qq_36162529/article/details/103700485