以前項目採用了react-intl作多語言切換,記錄一下。react
大致的實現原理和react-redux的實現原理相似,最外層包一個Provider,利用getChildContext,將intlConfigPropTypes存起來,在FormattedMessage、FormattedNumber等組件或者調用injectIntl生成的高階組件中使用,來完成國際化的。
git
使用過程也很是簡單,和react-redux的使用方法很是相似。json
目前咱們管理資源文件的方式是在 src/locales 文件夾下:redux
.
├── en-US.js
├── en-US.messages.js
├── zh-CN.js
└── zh-CN.messages.js複製代碼
注意: 文件命名、變量命名,是有規律的bash
*.messages.js 是咱們的資源文件(這裏咱們採用了 js 格式,你也能夠使用 json 等等),返回的是一個對象,key 爲咱們翻譯用的 id,value 爲具體語言的翻譯,內容是:antd
const login={
'username':'Username',
'new_user':'new user?'
}
const reset={
'reset.title':'Reset Your Password',
}
const en_US = {
...login,
...reset
};
export default en_US;複製代碼
en-US.js 文件封裝了 messages、locale 等國際化上下文組件須要的內容:app
import datePickerLocale from 'antd/lib/date-picker/locale/en_US';
import appLocaleData from 'react-intl/locale-data/en';
import messages from './en-US.messages.js';
import antdEn from 'antd/lib/locale-provider/en_US';
window.appLocale = {
// 合併全部 messages,加入 antd 組件的 messages
messages: Object.assign({}, messages, {
datePickerLocale,
}),
// locale語言標記
locale: 'en-US',
// react-intl locale-data
data: appLocaleData,
antd:antdEn,
// 自定義 formates
formats: {
date: {
normal: {
hour12: false,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
},
},
},
};
export default window.appLocale;
複製代碼
有了這些資源文件以及相關的封裝以後,咱們就能夠在 InltProvider
中使用了。
ide
能夠用Component來定義字符串:ui
<FormattedMessage
id="CopyButton.text"
defaultMessage="複製"
/>複製代碼
第二種,若是有些地方用不了Component,例如 Input 的this
injectIntl(Component);
this.props.intl.formatMessage(...);複製代碼
挖坑記錄
IntlProvider中的屬性變動並不會觸發FormattedMessage從新渲染,剛開始想要forceUpdate強制更新組件,後來上網查了一個解決方案,在組件中加入key,就能解決這個問題,但大型複雜項目不建議使用這種解決方案,由於會引發此<IntlProvider>
包裹下的全部組件所有被更新。