reactjs - intl.formatMessage 不起作用-react-intl

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

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

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

最佳答案

您需要调用formatMessageMessageDescriptor ,不仅仅是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 组件相同的 props:

formatMessage({id: 'hello'})

关于reactjs - intl.formatMessage 不起作用-react-intl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44832683/

相关文章:

javascript - Redux 形式 : how to handle errors in form component

ajax - 使用 JEST 进行 ajax 调用的单元测试 React 组件

javascript - ReactJS 使用 Props 数组改变表单输入

reactjs - 删除子项的惯用方法

reactjs - React 组件的生命周期、状态和 redux

javascript - 在 React 15.1.0 上重写一个 React-Addons 功能

reactjs - 将 react router V6 导航与 redux 和 redux thunk 操作一起使用的最佳方法是什么?

react-native - 使用 redux 进行 native react : Can we have initial payload for actions

forms - 使用 FieldArray 字段初始化 redux 表单

javascript - JavaScript 中无异步的执行顺序