react intl 国际化

2018-06-24 00:57:47来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

方案描述:由于采用单页面,所以按钮切换时会刷新页面 

1、安装 react-intl  babel-plugin-react-intl json-loader

npm i  react-intl  babel-plugin-react-intl json-loader --save-dev

 

2、修改webpack.config.js 与 webpack.production.config.js

entry: {
  en_US: path.resolve(__dirname, './en-US.js'),
  zh_Hans_CN: path.resolve(__dirname, './zh-CN.js'),
  index: path.resolve(__dirname, 'react/inxex.js')
},
output: {
  path: __dirname + '/build',
  publicPath: '/build',
  filename: '[name].js',
  chunkFilename: "[id].[name].js"
},

 

3、新建 index-en.html/ index-zh.html
index-en.html  引入 
    <script src="/build/en-US.js"></script>
    <script src="/build/index.js"></script>

index-zh.html同理

 

4、新建文件夹locals   创建 en.json/zh.json
en.json
{
"Home.Title": "username", "Home.BUtton": "login" }

 

zh.json
{
  "Home.Title": "用户名",
  "Home.BUtton": "登录"
}

 

5、在入口文件目录下新建 en-US.js、zh-CN.js
import antdEn from 'antd/lib/locale-provider/en_US';
import appLocaleData from 'react-intl/locale-data/en';
import MSGS from './locals/en.json';
import MSGS1 from './M/en.json'

window.appLocale = {
  messages: {
    ...MSGS,
    ...MSGS1
  },
  antd: antdEn,
  locale: 'en-US',
  data: appLocaleData,
};

 

6、入口文件index.js
import ReactDOM from 'react-dom';
import React from 'react';
import App from '../component/App';
import { LocaleProvider } from 'antd';

import { addLocaleData, IntlProvider } from 'react-intl';

const appLocale = window.appLocale;

addLocaleData(appLocale.data);

ReactDOM.render(
  <LocaleProvider locale={appLocale.antd}>
    <IntlProvider locale={appLocale.locale} messages={appLocale.messages}>
      <App />
    </IntlProvider>
  </LocaleProvider>,
  document.getElementById('react-content')
);

 

7、app中使用
import React from 'react';
import { DatePicker, Pagination, Table, Icon  } from 'antd';
import { FormattedMessage, defineMessages } from 'react-intl';
import InjectExample from './InjectExample';

const messages = defineMessages({
  datePicker: {
    id: 'App.datePicker.title',
    defaultMessage: '日期选择',
  },
  name: {
    id: 'App.talbe.name',
    defaultMessage: '姓名',
  }
});

class App extends React.Component {
  componentDidMount() {
   console.log('componentDidMount') 
  }
  render() {return (<div style={{ margin: 20 }}>
      <div style={{ margin: 10 }}>
        <p><a href="index.html">中文</a></p>
        <p><a href="index-en.html">english</a></p>
      </div>
      <div style={{ margin: 10 }}>
        <FormattedMessage {...messages.datePicker} />: &nbsp;
        <DatePicker />
      </div>
      
    </div>);
  }
}

export default App;

 

参考demo: https://github.com/yangstar/intl-example

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:select2 3.5.3 二级下拉及搜索

下一篇:关于在bootstrap的tab栏中渲染echats图表,切换tab时echats不显