我想使用formatMessage
的功能react-intl
API 插入消息作为占位符,但我无法找出访问此函数的正确方法。
这是我所拥有的简化版本:
// 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(使用前将#替换为@)