首页 > 解决方案 > 如何在 Typescript 中输入匹配项?

问题描述

我有一个必须使用 match.params 的组件,但是当我尝试它时出现错误。在我的情况下如何获得匹配参数?

零件


type MainInfoProps = {
  mainInfo: IUser,
  boxShadow?: number,
};

export const UserCard: React.FC<MainInfoProps> = (props) => {
  return()
}

错误

Property 'match' does not exist on type 'PropsWithChildren<MainInfoProps>'

标签: reactjstypescriptreact-router-dom

解决方案


您应该使用RouteComponentPropswhich 是接受params对象类型的泛型类型。

import { RouteComponentProps } from 'react-router-dom';

type MainInfoProps = {
   mainInfo: IUser;
   boxShadow?: number;
} & RouteComponentProps<{ paramOne: string; paramTwo: string }>;

然后你就可以使用它了:

props.match.params.paramOne;

推荐阅读