i18n
Getting Started#
Pro implements globalization through the umi plugin umi-plugin-locale and is enabled by default. umi-plugin-locale
convention Introduces the corresponding js in src/locales, such as en-US.js and zh-CN.js, And do the following configuration in config/config.js
:
plugins:[
...,
locale: {
enable: true,
default: 'zh-CN',
baseNavigator: true,
},
....
]
I am happy to use the function of globalization. See config。
umi-plugin-locale
encapsulates react-intl, api is basically the same as react-intl
, and is more convenient to package. All apis are as follows:
import { formatMessage, setLocale, getLocale, FormattedMessage } from 'umi/locale';
Formatt Message#
If we have the following configuration in en-US.js
and zh-CN.js
respectively:
// zh-CN.js
export default {
'navbar.lang': '中文',
}
// en-US.js
export default {
'navbar.lang': 'English',
}
We can use this in the component
import { FormattedMessage } from 'umi/locale';
export default () => {
return (
<div>
<FormattedMessage id="navbar.lang" />
</div>
);
};
In some cases, you may need to return a string directly. You can use it like this:
import { formatMessage } from 'umi/locale';
export default () => {
return <div>{formatMessage({ id: 'navbar.lang' })}</div>;
};
Set Locale#
umi-plugin-locale
exposes apis named setLocale
and getLocale
, which make it easy to switch between regions. The code like this:
...
changLang = () => {
const locale = getLocale();
if (!locale || locale === 'zh-CN') {
setLocale('en-US');
} else {
setLocale('zh-CN');
}
};
render(){
<Button
size="small"
ghost={theme === 'dark'}
style={{
margin: '0 8px',
}}
onClick={() => {
this.changLang();
}}
>
<FormattedMessage id="navbar.lang" />
</Button>
}
More advanced usage can be found in react-intl's api.