react-intl,将api与Typescript一起使用 [英] React-intl, use api with Typescript

查看:536
本文介绍了react-intl,将api与Typescript一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用react-intl API的formatMessage函数插入一条消息作为占位符,但是我不知道访问该函数的正确方法.

I would like to use the formatMessage function of the react-intl API to insert a message as placeholder, but I can't figure out the right way to access this function.

这是我所拥有的东西的简化版本:

Here is a simplified version of what I have :

//index.tsx
<IntlProvider locale={`fr-FR`} messages={messages_fr}>
    <NameForm/>
</IntlProvider>,

//nameForm.tsx
interface NameFormProps {
   intl?: InjectedIntlProps,
}

export default injectIntl(NameForm);

class NameForm extends React.Component<NameFormProps, {}> {

render() {
    let namePlaceholder = this.props.intl.formatMessage(
        {id: "NAME_PLACEHOLDER",
        defaultMessage: "name"
    });

    return (
        <form>
            <input placeholder={namePlaceholder} type="text"/>
        </form>
    );
}

因为IntlShape似乎没有提供formatMessage方法,所以我将InjectedIntlProps用作intl道具的类型.

I used InjectedIntlProps as type of the intl prop, because IntlShape didn't seems to offer a formatMessage method.

我添加了一个?因为我一直有一个"Property'intl is missing"(但injectIntl​​不应该返回没有该prop的组件吗?)

I Added a ? to the intl prop because I kept having a "Property 'intl' is missing" (but isn't injectIntl supposed to return a component without this prop ?)

现在它可以编译了,但是在运行时出现错误(我猜是无法读取未定义的属性'displayName'的未定义"),因为默认导出没有明确的名称.

Now it compiles, but when running I get an error ("Cannot read property 'displayName' of undefined" I guess because the default export doesn't have an explicit name).

我觉得我没有朝着正确的方向前进,但是找不到打字稿/react-intl项目的任何示例.

I feel I'm not going in the right direction, but can't find any example of a typescript/react-intl project.

感谢您的帮助!

推荐答案

该问题归因于打字稿定义的版本. 使用@ types/react-intl:" ^ 2.2.0时,它就像一个超级按钮.

The problem was due to the version of the typescript definition. When using @types/react-intl": "^2.2.0", it works like a charm.

(编辑)使其工作所需的少量更改:

(edit) Few changes needed to make it work :

//index.tsx
<IntlProvider locale={`fr-FR`} messages={messages_fr}>
  <NameForm/>
</IntlProvider>,

//nameForm.tsx
interface NameFormProps extends InjectedIntlProps {
  placeholder: string,
}

class NameForm extends React.Component<NameFormProps, {}> {

  render() {
    let namePlaceholder = this.props.intl.formatMessage({
       id: this.props.placeholder,
       defaultMessage: "name"
      });

    return (
      <form>
        <input placeholder={namePlaceholder} type="text"/>
      </form>
    );
}

export default injectIntl(NameForm);

这篇关于react-intl,将api与Typescript一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆