【问题标题】:intl.formatMessage not working - react-intlintl.formatMessage 不起作用 - react-intl
【发布时间】:2017-12-03 14:24:51
【问题描述】:

我正在尝试使用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')
);

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

【问题讨论】:

  • 检查 props 是否正确通过。
  • 我希望我正确传递道具。你能告诉我你说的是什么道具吗?
  • 国际道具。你能解释一下你遇到了什么错误吗?
  • 我不知道国际道具。但我收到此错误Uncaught Error: [React Intl] An 'id' must be provided to format a message.
  • 你是塔米赞人吗?我是塔米赞人。我不知道。我会参考并分享我的知识。

标签: reactjs redux react-redux react-intl babel-plugin-react-intl


【解决方案1】:

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

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

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

<FormatMessage id="Hello" />

Props 实际上是一个键值字典:

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

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

formatMessage({id: 'hello'})

【讨论】:

  • Tomas,您的解决方案确实有效。我确实将昨天的代码放在了其他文件中,今天它也给我带来了错误。对于那个很抱歉。您的解释更清楚。非常感谢!随着时间的推移,我会删除我之前的评论。
【解决方案2】:

此外,您似乎缺少它的默认值。

 <FormattedMessage id="footer.table_no" defaultMessage="Hello" />

【讨论】:

    【解决方案3】:

    在尝试使用动态值但失败后,我发现如果const intlKey = "something"

    {intl.formatMessage({ id: intlKey })} //this doesn't work
    {intl.formatMessage({ id: `${intlKey}` })} //this works
    
    <IntlMessages id={intlKey} /> //this doesn't work
    <IntlMessages id={`${intlKey}`} /> //this works
    

    因此将您的值字符串化(即使确定它是一个字符串)以便 intl 工作。

    【讨论】:

      猜你喜欢
      • 2012-11-16
      • 2018-11-15
      • 2016-06-04
      • 2014-01-04
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      相关资源
      最近更新 更多