React-intl相关使用介绍

  React-intl用于国际化react组件,提供react组件和api来格式化日期、数字,字符等等。其中一个很重要的功能是实现文本翻译,将你所做的中文版应用所有文字转为英文。

  关于配置什么的,请参照:https://www.jianshu.com/p/574f6cea4f26,个人觉得讲的很详细。

  下面只说说在react项目中的使用方式。

  

  第一步 导入资源,初始化

  第二步 在具体的组件中进行使用

  方式一 FormattedMessage返回一个html tag

  对于tag,直接使用FormattedMessage, 本方式返回的是一个tag对象.
  注意FormattedMessage只适用没有attributes的tag,如果带有className或者style的话,请使用第二种方式.

js
import {
  FormattedMessage,
} from 'react-intl'

return (
  <FormattedMessage tagName="small" id="intl.xxx" default="" />
)

  方式二 injectIntl 返回一段字符串

js
import {
  intlShape,
  injectIntl,
} from 'react-intl'


class Comp extends Component {
  static propTypes = {
    intl: intlShape.isRequired,
  };
  render() {
    const { formatMessage } = this.props.intl
    return (
      <p className="cn">{formatMessage({ id: 'intl.xxx' })}</p>
    )
  }
}
 
原文地址:https://www.cnblogs.com/chenbeibei520/p/10979398.html