我正在努力让我了解Typescript和React Router。我一直在努力...
我当前收到错误消息:
类型'RouteComponentProps <{},StaticContext,any>'。ts(2339)“`
中不存在属性'params'
import React from "react";
import { RouteComponentProps } from "react-router-dom";
const TopicDetail = ({ match }: { match: RouteComponentProps }) => {
return (
<div>
<h3>{match.params.topicId}</h3>
~~~~~~
</div>
);
};
export default TopicDetail;
我可以通过定义自己的interface
来消除错误,但是我不知何故认为这样做是错误的方式:
import React from "react";
interface Props {
params: any;
}
const TopicDetail = ({ match }: { match: Props }) => {
return (
<div>
<h3>{match.params.topicId}</h3>
</div>
);
};
export default TopicDetail;
答案 0 :(得分:2)
为路由器参数道具定义接口是推荐的方法,尽管您可以使用接口声明更加明确。在声明组件的props接口时,可以extend
RouteComponentProps
并将特定的params接口用作类型变量。
例如:
import React from "react";
import { withRouter, RouteComponentProps } from "react-router-dom";
interface RouterProps { // type for `match.params`
topicId: string; // must be type `string` since value comes from the URL
}
interface TopicDetailProps extends RouteComponentProps<RouterProps> {
// any other props (leave empty if none)
}
const TopicDetail: React.FC<TopicDetailProps> = ({ match }) => {
return (
<div>
<h3>{ match.params.topicId }</h3>
</div>
)
}
export default withRouter(TopicDetail);