JavaScript @umijs/plugin-locale插件使用教程
介紹
plugin-locale是一個國際化的插件,用于解決i18n問題,約定式的多語言支持,可以進行多個國際語言的切換
啟用方式
在umirc.ts文件中配置locale:{}開啟
使用
在src下創(chuàng)建一個locales文件夾,在文件夾下配置我們的語言文件
中文語言文件:zh-CN.js
export default {
WELCOME_TO_UMI_WORLD: '{name},歡迎光臨umi的世界',
};英文語言文件:en-US.js
export default {
WELCOME_TO_UMI_WORLD: "{name}, welcome to umi's world",
};注意:如果項目配置了singular: true,locales要改成locale
App.ts配置
import zhTW from 'antd/es/locale/zh_TW';
import {addLocale} from 'umi'
// 動態(tài)增加新語言
addLocale(
'zh-TW',
{
// id 列表
name: '妳好,{name}',
},
{
momentLocale: 'zh-tw',
antd: zhTW,
},
);動態(tài)的增加語言,增加語言之后可以通過getAllLocales獲取列表
addLocale 三個參數(shù)。
name語言的 key。例如 zh-TWmessage語言的 id 列表。 例如:{// id 列表 name: '妳好,{name}',}- 相應(yīng)的
momentLocale和antd配置
配置完以上代碼之后,我們需要重新運行一下項目,頁面可能會報一些紅色波浪線錯誤,但不影響使用,原因是ts類型問題,如果不想報紅色波浪線,可以在后面加上:any,這是最快的解決方案,但是一般不推薦使用
在組件中使用
getAllLocales
獲取當(dāng)前獲得所有國際化文件的列表,默認會在locales文件夾下尋找類似en-US.(js|json|ts)文件
import { getAllLocales } from 'umi';
console.log(getAllLocales()); // [en-US,zh-CN,...]getLocale
獲取當(dāng)前選擇的語言
import { getLocale } from 'umi';
console.log(getLocale()); // en-US | zh-CNuseIntl
useIntl是最常用的 api,它可以獲得formatMessage等 api 來進行具體的值綁定
import styles from './index.less';
import { getAllLocales } from 'umi';
import { useIntl} from 'umi';
export default function IndexPage() {
const intl = useIntl();
console.log(intl);
return (
<div className={styles.title}>
<h1>Page index</h1>
<div>{intl.messages.WELCOME_TO_UMI_WORLD}</div>
</div>
);
}通過useIntl可以把我們的語言文件中內(nèi)容渲染到頁面
setLocale
設(shè)置切換語言,默認會刷新頁面,可以通過設(shè)置第二個參數(shù)為false,來實現(xiàn)無刷新動態(tài)切換
import styles from './index.less';
import { getAllLocales } from 'umi';
import { useIntl, setLocale } from 'umi';
export default function IndexPage() {
const intl = useIntl();
console.log(intl);
console.log(getAllLocales()); // [en-US,zh-CN,...]
return (
<div className={styles.title}>
<h1>Page index</h1>
<div>{intl.messages.WELCOME_TO_UMI_WORLD}</div>
<button
onClick={() => {
setLocale('zh-CN', false);
}}
>
切換中文
</button>
<button onClick={() => {
setLocale('en-US', false);
}}>切換英文</button>
</div>
);
}給定了兩個button按鈕,可以做語言的切換
以上是plugin-locale的簡單操作,詳情請查看umi官網(wǎng)@umijs/plugin-locale
到此這篇關(guān)于JavaScript @umijs/plugin-locale插件使用教程的文章就介紹到這了,更多相關(guān)JS @umijs/plugin-locale內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
遍歷json 對象的屬性并且動態(tài)添加屬性的實現(xiàn)
下面小編就為大家?guī)硪黄闅vjson 對象的屬性并且動態(tài)添加屬性的實現(xiàn)。小編覺的挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12

