简体   繁体   中英

react on rails / react intl

I am trying to implement i18n for a rails/react_on_rails project following this guide; https://github.com/shakacode/react_on_rails/blob/master/docs/basics/i18n.md

I get the error "formatMessage is not defined", so I am probably missing something, here is my code:

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>

    );
  }
}

You get the exact error message:

formatMessage is not defined

I've been using react-intl so what I believe you need to do is first to inject intl object. You can read about it in the react-intl documentation. Try this:

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);

I bet it will work.

Or even simpler just change this:

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>

    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM