React-intl,将 api 与 Typescript 结合使用

2024-01-25

我想使用formatMessage的功能react-intlAPI 插入消息作为占位符,但我无法找出访问此函数的正确方法。

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

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

I used InjectedIntlProps作为类型intl道具,因为IntlShape似乎没有提供formatMessage method.

我添加了一个?到intl道具因为我一直有一个Property 'intl' is missing(但不是injectIntl应该返回一个没有这个 prop 的组件?)

现在可以编译了,但是运行时出现错误Cannot read property 'displayName' of undefined。我猜这是因为默认导出没有明确的名称)。

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

感谢您的帮助!


在处理同样的问题时,我发现都不包括InjectedIntlProps作为问题中提到的成员,或者另一个答案中提到的从其延伸的成员,都满足类型检查器的要求。当从InjectedIntlProps,调用injectIntl已检查,但在 JSX 中使用生成的组件希望我提供一个intl财产。不过,以下策略解决了这个问题:

    interface NameFormProps {
        // Include all custom properties here.
    }

    class NameForm extends React.Component<NameFormProps & InjectedIntlProps, {}> {
        // Class body.
    }

    export default injectIntl(NameForm);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React-intl,将 api 与 Typescript 结合使用 的相关文章

随机推荐