如何在React Router中使用Typescript并进行匹配

时间:2019-08-25 21:35:48

标签: reactjs typescript react-router

方法

我正在努力让我了解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;

1 个答案:

答案 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);