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

Nic*_*nco 46 typescript reactjs react-router

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

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

export class ProductContainer extends React.Component<Props> {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

Naz*_*554 85

您不需要显式添加它.您可以使用RouteComponentProps<P>from @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;
}
Run Code Online (Sandbox Code Playgroud)

  • @KarlRichter [`从'history'中导入*作为H;`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/f6f3254c89ea03010d51533262ce7d1094b32607/types/react-router/index.d.ts#L28) (3认同)
  • 这样做的问题是,Typescript 期望该组件的每次使用都实际传递到位置历史记录等道具中。RouteComponentProps 应该将这些道具作为可选。必须用 Partial 换行。 (2认同)

The*_*inn 10

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

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

interface MatchParams {
    name: string;
}

interface MatchProps extends RouteComponentProps<MatchParams> {
}
Run Code Online (Sandbox Code Playgroud)

此外,为了允许可重用​​的组件,该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>)
}
Run Code Online (Sandbox Code Playgroud)


daw*_*ski 10

简单的解决方案

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

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