在 rails 上做出反应/在国际上做出反应

react on rails / react intl

我正尝试按照本指南为 rails/react_on_rails 项目实施国际化; https://github.com/shakacode/react_on_rails/blob/master/docs/basics/i18n.md

我收到错误 "formatMessage is not defined",所以我可能遗漏了一些东西,这是我的代码:

import PropTypes from 'prop-types';
import React from 'react';
import { IntlProvider } from 'react-intl';

import { addLocaleData } from 'react-intl';
import en from 'react-intl/locale-data/en';
import nb from 'react-intl/locale-data/nb';
import { translations } from '../../../libs/i18n/translations';
import { defaultLocale } from '../../../libs/i18n/default';

// Initizalize all locales for react-intl.
addLocaleData([...en, ...nb]);

// set locale and messages for IntlProvider.
// const locale = method_to_get_current_locale() || defaultLocale;
const locale = defaultLocale;
const messages = translations[locale];

import { defaultMessages } from '../../../libs/i18n/default';


export default class TextMessage extends React.Component {

  render() {
    return (
      <IntlProvider locale={locale} key={locale} messages={messages}>   
        { formatMessage(defaultMessages.ActionsYes) }
      </IntlProvider>

    );
  }
}

您收到确切的错误消息:

formatMessage is not defined

我一直在使用 react-intl 所以我相信你需要做的是首先注入 intl 对象。您可以在 react-intl 文档中阅读相关信息。试试这个:

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

...

class TextMessage extends React.Component {


  render() {

    return (
      <IntlProvider locale={locale} key={locale} messages={messages}>
        { this.props.intl.formatMessage(defaultMessages.ActionsYes) }
      </IntlProvider>

    );
  }
}

export default injectIntl(TextMessage);

我打赌它会起作用。

或者更简单的只是改变这个:

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

...

export default class TextMessage extends React.Component {
  render() {
    return (
       <IntlProvider locale={locale} key={locale} messages={messages}>
        <FormattedMessage {...defaultMessages.ActionsYes} />
       </IntlProvider>

    );
  }
}