方案描述:由於採用單頁面,所以按鈕切換時會刷新頁面 1、安裝 react-intl babel-plugin-react-intl json-loader 2、修改webpack.config.js 與 webpack.production.config.js entry: { en_US: pat ...
方案描述:由於採用單頁面,所以按鈕切換時會刷新頁面
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} />: <DatePicker /> </div> </div>); } } export default App;
參考demo: https://github.com/yangstar/intl-example