加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – intl.formatMessage不工作 – react-intl

发布时间:2020-12-15 20:13:05 所属栏目:百科 来源:网络整理
导读:我正在尝试使用react-intl进行语言翻译.当我使用这个 FormattedMessage id ='importantNews'/时,它是完美的.但是当我在intl.formatMessage()中使用以下代码时,它不起作用并抛出一些错误.我不知道它有什么问题. import { injectIntl,FormattedMessage } from
我正在尝试使用react-intl进行语言翻译.当我使用这个< FormattedMessage id ='importantNews'/>时,它是完美的.但是当我在intl.formatMessage()中使用以下代码时,它不起作用并抛出一些错误.我不知道它有什么问题.

import { injectIntl,FormattedMessage } from 'react-intl';

function HelloWorld(props) {
  const { intl } = props;
  const x = intl.formatMessage('hello') + ' ' + intl.formatMessage('world'); //not working
  const y = <FormattedMessage id='hello' />; //working
  return (
    <button>{x}</button>
  );
}

export default injectIntl(HelloWorld);

我的根组件是这样的,

import ReactDOM from 'react-dom';
import { addLocaleData,IntlProvider } from 'react-intl';
import enLocaleData from 'react-intl/locale-data/en';
import taLocaleData from 'react-intl/locale-data/ta';

import HelloWorld from './hello-world';

addLocaleData([
  ...enLocaleData,...taLocaleData
]);

const messages = {
  en: {
    hello: 'Hello',world: 'World'
  },ta: {
    hello: '???????',world: '?????'
  }
};

ReactDOM.render(
  <IntlProvider key={'en'} locale={'en'} messages={messages['en']}>
    <HelloWorld />
  </IntlProvider>,document.getElementById('root')
);

有人可以帮我解决这个问题吗?提前致谢.

解决方法

您需要使用 MessageDescriptor调用 formatMessage,而不仅仅是id:

const x = intl.formatMessage({id: 'hello'}) + ' ' + intl.formatMessage({id: 'world'});

为了更好地记住这一点 – 使用prop id调用组件:

<FormatMessage id="Hello" />

道具实际上是一个键值字典:

// this is the same as above
<FormatMessage {...{id: 'hello'}} />

现在,formatMessage函数接受与FormatMessage组件相同的道具:

formatMessage({id: 'hello'})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读