React-intl,与Typescript一起使用API
问题描述:
我想使用react-intl API的formatMessage函数来插入一个消息作为占位符,但我找不出正确的方式来访问这个函数。React-intl,与Typescript一起使用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>
);
}
我用InjectedIntlProps类型的国际道具,因为IntlShape没有似乎提供了一个FORMATMESSAGE方法。
我增加了一个?到intl道具,因为我一直有一个“属性”intl'缺少“(但不injectIntl应该返回一个组件没有这个道具?)
现在它编译,但运行时出现错误(”无法读取属性'displayName'的未定义“我猜是因为默认导出没有明确的名称)。
我觉得我不会走向正确的方向,但找不到任何typecript/react-intl项目的例子。
感谢您的帮助!
答
问题是由于打字稿定义的版本。 当使用@类型/反应-国际“:‘^ 2.2.0’,它就像一个魅力
(编辑),使需要一些改变它的工作:虽然与工作
//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);
答
同样的问题,我发现包括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);
答
现有的解决方案都不适用于我。相反,这是由于injectIntl
推断的属性包含InjectedIntlProps
。
要解决它,我必须明确地告诉injectIntl
什么道具包裹组件应具备:
interface NameFormProps {
}
class NameForm extends React.Component<NameFormProps & InjectedIntlProps> {
}
export default injectIntl<NameFormProps>(NameForm);
如果没有道具,它需要稍微改变:
class NameForm extends React.Component<InjectedIntlProps> {
}
export default injectIntl<{}>(NameForm);
没” t为我工作......但改变“扩展React.Component”为“扩展React.PureComponent”。 – karfus
对我来说同样重要......导出类后,“导出默认值”必须出现! – karfus
我再次编辑它。事实上,您需要将输出行放在文件末尾,您可以扩展“InjectedIntlProps”而不是手动添加intl道具 – Emarco