大家好,又见面了,我是你们的朋友全栈君。
最近做的react项目需要支持国际化,网上查了一下,发现一款很好的插件“react-intl-universal”,由阿里巴巴团队开发,这款插件是原先的国际化插件“react-intl”的升级版,“react-intl”因为一些“致命”缺陷现已被其取代,npm官网有罗列原因,有兴趣的可以去了解一下。下面具体介绍一下这款插件的使用方法。
npm install react-intl-universal --save1.配置语言包,json文件根据需要支持几种语言来决定,下面的图片中仅支持中英文:

2.于项目入口文件中配置国际化
import intl from 'react-intl-universal';
 
// locale data
const locales = {
  "en-US": require('./locales/en-US.js'),
  "zh-CN": require('./locales/zh-CN.js'),
};
 
class App extends Component {
 
  state = {initDone: false}
 
  componentDidMount() {
    this.loadLocales();
  }
 
  loadLocales() {
    // init method will load CLDR locale data according to currentLocale
    // react-intl-universal is singleton, so you should init it only once in your app
    intl.init({
      currentLocale: 'en-US', // TODO: determine locale here
      locales,
    })
    .then(() => {
      // After loading CLDR locale data, start to render
      this.setState({initDone: true});
    });
  }
 
  render() {
    return (
      this.state.initDone &&
      <div>
        {intl.get('SIMPLE')}
      </div>
    );
  }
 
}1.在component中导入插件
import intl from 'react-intl-universal';2.html中引用资源包里的文字
a.纯文字,使用intl.get()
<div> {intl.get('SIMPLE')} </div>b.带html模板的文字,使用intl.getHTML()方法
例如资源包里是这样定义的
{ 
   "SIMPLE": "This is <span style='color:red'>HTML</span>" 
}引用时需使用getHTML()方法获取文字
<div>{intl.getHTML('SIMPLE')}</div>3.配置默认message
当遇到比如因拼写错误导致无法匹配到资源包里的文字时,可以事先配置默认的message,这时当无法匹配的资源包时会显示默认message
//"defaultMessage()"可简写为"d()"
intl.get('not-exist-key').defaultMessage('没有找到这句话');同理亦可配置带html模板的默认message
intl.getHTML('not-exist-key').d(<h2>没有找到这句话</h2>)4.带变量的message
资源包里的配置如下
{
    "HELLO": "Hello, {name}. Welcome to {where}!" 
}在html中引用时
<div> intl.get('HELLO', {name:'banana', where:'China'}) </div>显示的结果为:Hello, banana. Welcome to China!
5.数字形式和千分位分隔符
是第四种用法的延伸,举例:
下例中的变量为num,给它标记为plural后,它的值只能为数字。当num值为0时,显示”no photos.”;当值为1时,显示”one photo.”;当值为其他数字比如25000时,显示“25,000 photos.”,这里的’#’表示给num的值添加千分位分隔符后显示
{ 
   "PHOTO": "You have {num, plural, =0 {no photos.} =1 {one photo.} other {# photos.}}" 
}引用结果如下:
intl.get('PHOTO', {num:0}); // "You have no photos."
intl.get('PHOTO', {num:1}); // "You have one photo."
intl.get('PHOTO', {num:1000000}); // "You have 1,000,000 photos."6.显示货币格式
具体语法为{变量名, 类型, 格式化},下例中变量名为”price”,它的类型是number,”USD”表示在值前面加上美元符号($)
{ 
   "SALE_PRICE": "The price is {price, number, USD}" 
}引用及显示结果如下:
intl.get('SALE_PRICE', {price:123456.78}); // The price is $123,456.787.显示日期
语法同上:{变量名, 类型, 格式化},当类型为”date”时,格式化有以下几个选项:short,medium,long,full,也可不格式化
{
  "SALE_START": "Sale begins {start, date}",
  "SALE_END": "Sale ends {end, date, long}"
}引用及显示:
intl.get('SALE_START', {start:new Date()}); // Sale begins 4/19/2017
intl.get('SALE_END', {end:new Date()}); // Sale ends April 19, 2017我的例子可下载核心代码查看
链接: https://pan.baidu.com/s/1W7cR3_4iAO_nWDzuaVmX0w
密码: a6mm
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/128875.html原文链接:https://javaforall.cn