【发布时间】:2019-11-20 13:42:49
【问题描述】:
我正在尝试对 React+Typescript 进行更深入的了解和实践,在使用来自 react-router-dom 的 withRouter 时遇到了这个打字错误。
我的代码 sn-p 非常简单,我尝试找出有相同问题的人,其中一些答案指出升级时出错(但它们是从 2016 年开始的,所以......)和他们中的一些人使用了我没有使用的connect() 语句(这导致了一个问题,“我这样做是因为不使用它而做错了吗?”)。我看到其中一些建议还涉及将 Props 映射到 State,直到现在我还没有做过(也没有见过)。我希望有人对我缺少什么以及我应该查看的其他内容提出一些建议。
代码是:
import React from "react";
import { withRouter } from "react-router-dom";
interface ISection {
id: number;
title: string;
imageUrl: string;
size: string;
}
class MenuItem extends React.Component<ISection> {
render() {
return (
<div className={`${this.props.size} menu-item`}>
<div
className="background-image"
style={{ backgroundImage: `url(${this.props.imageUrl})` }}
/>
<div className="content">
<h1 className="title">{this.props.title}</h1>
<span className="subtitle">some subtitle</span>
</div>
</div>
);
}
}
export default withRouter(MenuItem);
我期望从这里顺利工作(我不得不说我首先尝试了一个功能组件,因为我没有任何状态,但是我看到的所有解决方案都涉及一个类组件,所以我移动了它进入它),但我在最后一行的MenuItem 上收到以下错误:
Argument of type 'typeof MenuItem' is not assignable to parameter of type 'ComponentClass<RouteComponentProps<any, StaticContext, any>, any> | FunctionComponent<RouteComponentProps<any, StaticContext, any>> | (FunctionComponent<RouteComponentProps<any, StaticContext, any>> & ComponentClass<...>) | (ComponentClass<...> & FunctionComponent<...>)'.
Type 'typeof MenuItem' is not assignable to type 'ComponentClass<RouteComponentProps<any, StaticContext, any>, any>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'RouteComponentProps<any, StaticContext, any>' is missing the following properties from type 'Readonly<ISection>': id, title, imageUrl, sizets(2345)
我的问题是:
为什么会显示“type 'typeof MenuItem'”?不应该只说'MenuItem'的类型而不是获取类型的函数吗?
withRouter 是否必须与类组件一起使用,还是对功能组件也有效?
我需要
connect()什么,或者将 Props 映射到 State 上吗?如果是,为什么?最后,我该如何解决这个问题?
【问题讨论】:
标签: typescript react-router react-router-dom