我应该在道具中使用哪种TypeScript类型来引用匹配对象?


Answers:


146

您无需显式添加。您可以改用RouteComponentProps<P>from@types/react-router作为道具的基本接口。P是您的比赛参数的类型。

import { RouteComponentProps } from 'react-router';

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

interface MatchParams {
    name: string;
}

interface Props extends RouteComponentProps<MatchParams> {
}
// from typings
import * as H from "history";

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
什么是H指什么?
Karl Richter)


1
问题是Typescript希望该组件的每次使用都在位置历史道具等中实际传递。RouteComponentProps应该将那些道具作为可选。必须用偏心包装。
Glstunna

1
@Glstunna感谢您让我知道,局部显示的效果如何?OP:请包括您的进口。
Toskan

非常感谢。这非常有用,因此我现在可以正确指定从URL中获得的期望
danivicario

27

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

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

interface MatchParams {
    name: string;
}

interface MatchProps 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>)
}

太棒了!不错的补充
Rey Wang

0

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

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

export const CreditPortfolioDetail: FC<RouteComponentProps<MatchParams>> = (props) => {
    const { firstParam, optionalParam} = props.match.params; 
    // ...
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.