(一)需要
我的项目须要中英文切换。须要将我的项目做中文 / 英文切换。来满足英语语言的展现和拜访需要。
(二)剖析
1、我的项目至多须要反对中英文切换。
2、须要切换的内容分为:
- 组件的中英文切换;
- 菜单、题目、表单等其余内容的中英文切换。
(三)实现
1、Ant Design Pro 组件库
官网反对了配置,链接如下:
https://ant.design/components…
2、菜单、题目等其余内容
须要填写中英文两种文字的对照版本——两个文件别离对应文本不同的翻译内容,切换语言后,做不同的展现。
(四)代码
1、在 src 文件夹下新建了 lang 文件夹
有三个子文件
// cn.ts
export default {
box: '框',
shortkey: '快捷键',
batchEditAttr: '批量批改属性',
selCheck: '抽检',
save: '保留',
submit: '提交',
};
// en.ts
export default {
box: 'box',
shortkey: 'shortkey',
batchEditAttr: 'batchEditAttr',
selCheck: 'selCheck',
save: 'save',
submit: 'submit',
};
// index.ts
import cn from '@/lang/cn';
import en from '@/lang/en';
export default {
'zh-cn': cn,
en,
};
2、src 文件新建了 common 文件夹
蕴含了解决多语言的公共办法
// antdLocale.ts
import enUS from 'antd/lib/locale/en_US';
import zhCN from 'antd/lib/locale/zh_CN';
import lang from '@/lang/index';
import moment from 'moment';
export const localeMap = {
en: enUS,
'zh-cn': zhCN,
};
export const utransLang = localStorage.utransLang
? localStorage.utransLang
: 'zh-cn';
export const setLocaleLang = (item) => {localStorage.utransLang = item;};
export const getLocalLang = () => {
const tmp = localStorage.utransLang ? localStorage.utransLang : 'zh-cn';
window.lang = lang[tmp];
// console.log(lang);
// debugger;
};
export const getAntdLang = () => {getLocalLang();
moment.locale(utransLang);
return localeMap[utransLang];
};
3、首页 Demo
// index.tsx
import styles from './index.less';
import React, {useState} from 'react';
import {
ConfigProvider,
Button,
DatePicker,
Space,
version,
Radio,
Col,
Row,
} from 'antd';
import type {RadioChangeEvent} from 'antd';
import enUS from 'antd/es/locale/en_US';
import zhCN from 'antd/es/locale/zh_CN';
import {
getAntdLang,
getLocalLang,
utransLang,
setLocaleLang,
} from '@/common/antdLocale';
export default function IndexPage() {if (!window.lang) {getLocalLang();
}
console.log(window.lang);
// debugger
const [locale, setLocal] = useState(utransLang);
const changeLocale = (e: RadioChangeEvent) => {console.log('changeLocale:', locale);
const localeValue = e.target.value;
// debugger
setLocaleLang(localeValue.locale);
getLocalLang();
// const href = window.location.href
// location.href = location.href
setLocal(localeValue);
};
const save = () => {console.log('click');
};
return (
<div>
<h1 className={styles.title}>Page index</h1>
<div className="App">
<h1>antd version: {version}</h1>
<Row>
<Col span={24}>
<Radio.Group value={locale} onChange={changeLocale}>
<Radio.Button key="en" value={enUS}>
English
</Radio.Button>
<Radio.Button key="cn" value={zhCN}>
中文
</Radio.Button>
</Radio.Group>
</Col>
</Row>
<Row>
<Col span={24}>
<ConfigProvider locale={locale}>
<Space
key={
locale
? locale.locale
: 'en' /* Have to refresh for production environment */
}
>
<DatePicker />
<Button type="primary" onClick={() => save()}>
{lang.submit}
</Button>
</Space>
</ConfigProvider>
</Col>
</Row>
</div>
</div>
);
}