一、案例描述
根据浏览器语言设置进行多国语翻译
二、前期准备
安装
npm install react-intl --save
react-intl 使用介绍
-
React-intl是FormatJS的一部分,内置实现Date/Number/Time的国际格式化;
-
可以自定义映射关系,完成值对之间的替换;
-
通过获取浏览器的language来设置显示中文/英文(通过自定义映射,而非自动全文转换);
常用于实现静态内容
,如按钮文字,公司名称的转换;
三、使用步骤
1.配置locale文件
将不同语言的翻译文件放在各自的js文件中,同一处文本的多种语言翻译使用相同的key
en_US.js
const search = {
'intl.search-info': 'Search for status/ID...',
};
const hub = {
'intl.complete-content': 'Total item(s): {totalNum}',
};
const enUS = {
...search,
...hub,
};
export default enUS;
ja_JP.js
const search = {
'intl.search-info': '状態・IDで検索する',
};
const hub = {
'intl.complete-content': 'アイテムの総数:{totalNum}',
};
const jaJP = {
...search,
...hub,
};
export default jaJP;
2.引入react-intl
App.jsx
import React, { useRef } from 'react';
import { IntlProvider } from 'react-intl';
import { SnackbarProvider } from 'notistack';
import Slide from '@material-ui/core/Slide';
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';
import PropTypes from 'prop-types';
import { MuiPickersUtilsProvider } from '@material-ui/pickers';
import DateFnsUtils from '@date-io/date-fns';
import * as dateFnlocales from 'date-fns/locale';
import ConfirmProvider from './components/confirmDialog/confirmProvider';
import { getLocaleLang } from './utils/packagFunc';
import './App.css';
import en from './lang/en_US';
import ja from './lang/ja_JP';
const langMap = {
en,
ja,
};
const App = function App({
children,
}) {
const snackBarRef = useRef();
const onClickDismiss = (key) => () => {
snackBarRef.current.closeSnackbar(key);
};
const action = (key) => (
<IconButton key="close" aria-label="Close" color="inherit" onClick={onClickDismiss(key)}>
<CloseIcon style={{ fontSize: '20px' }} />
</IconButton>
);
const locale = getLocaleLang(langMap);
return (
<IntlProvider
locale={locale}
messages={langMap[locale]}
defaultLocale={locale}
>
<SnackbarProvider
anchorOrigin={{
vertical: 'top',
horizontal: 'center',
}}
TransitionComponent={Slide}
ref={snackBarRef}
action={action}
hideIconVariant
>
<ConfirmProvider>
<MuiPickersUtilsProvider
locale={dateFnlocales[locale]}
utils={DateFnsUtils}
>
<div>
{children}
</div>
</MuiPickersUtilsProvider>
</ConfirmProvider>
</SnackbarProvider>
</IntlProvider>
);
};
App.propTypes = {
children: PropTypes.node.isRequired,
};
export default App;
3.引入方法
./utils/packagFunc.js
/**
* Switch the corresponding language according to the browser language configuration
* @param {*} langMap
* @returns
*/
export function getLocaleLang(langMap) {
const type = navigator.appName;
const lang = LANG_DEFAULT;
if (type === NET_TYPE) {
const langFormatter = navigator.language.split('-')[0];
if (!Object.prototype.hasOwnProperty.call(langMap, langFormatter)) {
return lang;
}
return langFormatter;
}
// Get the browser configuration language, and support ie5+ = = navigator systemLanguage
return navigator.userLanguage;
}
四、 备注
- 由于IntlProvider包裹一次即可生效,把它包裹在系统根组件最外层即可。
- locale用于国际化数字、日期等,默认为en,这里设置成浏览器语言;
- messages接受的是一个对象,即引入的语言包。