我应该使用什么TypeScript类型来引用我的道具中的匹配对象?

时间:2018-01-07 14:26:50

标签: reactjs typescript react-router

在我的React容器/组件中,我可以使用哪种类型来引用React Router DOM包含的match部分?

interface Props {
  match: any // <= What could I use here instead of any?
}

export class ProductContainer extends React.Component<Props> {
  // ...
}

4 个答案:

答案 0 :(得分:64)

您无需明确添加。您可以使用RouteComponentProps<P>中的@types/react-router作为道具的基本界面。 P是您的匹配参数类型。

// example route
<Route path="/products/:name" component={ProductContainer} />

interface MatchParams {
    name: string;
}

interface Props extends RouteComponentProps<MatchParams> {
}

// from typings
export interface RouteComponentProps<P> {
  match: match<P>;
  location: H.Location;
  history: H.History;
  staticContext?: any;
}

export interface match<P> {
  params: P;
  isExact: boolean;
  path: string;
  url: string;
}

答案 1 :(得分:4)

简单的解决方案

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

const Container = ({ match }: RouteComponentProps<{ showId?: string}>) => {
 const { showId } = match.params?.showId;//in case you need to take params
}

答案 2 :(得分:3)

要添加到上述@ Nazar554的答案中,应从RouteComponentProps导入react-router-dom类型,并按如下方式使用。

import {BrowserRouter as Router, Route, RouteComponentProps } from 'react-router-dom';

interface MatchParams {
    name: string;
}

interface Props extends RouteComponentProps<MatchParams> {
}

此外,为了允许可重用​​的组件,render()函数允许您仅传递组件所需的内容,而不传递整个RouteComponentProps的内容。

<Route path="/products/:name" render={( {match}: MatchProps) => (
    <ProductContainer name={match.params.name} /> )} />

// Now Product container takes a `string`, rather than a `MatchProps`
// This allows us to use ProductContainer elsewhere, in a non-router setting!
const ProductContainer = ( {name}: string ) => {
     return (<h1>Product Container Named: {name}</h1>)
}

答案 3 :(得分:1)

问题是,即使在为 match<Params> 创建接口之后,类型警告仍然存在。这是对我有用的代码:

interface MatchParams {
    firstParam: string;
    optionalParam?: string;
}

export const CreditPortfolioDetail: FC<RouteComponentProps<MatchParams>> = (props) => {
    const { firstParam, optionalParam} = props.match.params; 
    // ...
}