i18n 在 react-alert-template-basic 中

i18n in react-alert-template-basic

在我的应用程序中,我使用 react-alert-template-basic 来显示警报。在 API 中,我直接写文本,例如: this.props.alert.error('<some text>');

现在,我想对文本进行国际化。快速搜索后,我发现 react-intl 是最受欢迎的选择之一。在文档中,我发现如果在渲染时执行国际化,如下所示:

  <FormattedMessage
                id="welcome"
                defaultMessage={`Hello {name}, you have {unreadCount, number} {unreadCount, plural,
                  one {message}
                  other {messages}
                }`}
                values={{name: <b>{name}</b>, unreadCount}}
            />

我不知道如何将 react-intlreact-alert-basic-template 一起使用。后者直接需要字符串,而不是组件 FormattedMessage.

有人知道怎么做吗?如果没有,还有其他选择吗?

而不是 <FormattedMessage> 组件,使用 formatMessage 函数。您还需要 injectIntl HOC:

import React from 'react';
import {injectIntl, FormattedRelative} from 'react-intl';

const Component = ({intl}) => {
  this.props.alert.error(intl.formatMessage(...))

  // your component ...
}


export default injectIntl(Component);

另外,您可以考虑 lingui i18n library if you're at the beginning of your project (I'm the author). It's successor to react-intl and very similar in usage. There's a react tutorial,这个例子看起来像这样:

import React from "react"
import { withI18n } from "@lingui/react"

const Component = ({ i18n }) => {
  this.props.alert.error(i18n.t`some text`)

  // your component ...
}

export default withI18n(Component)