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

新手上路,请多包涵

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

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

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

原文由 Nicolas Blanco 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 385
2 个回答

您不需要显式添加它。您可以使用来自 RouteComponentProps<P>@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;
}

原文由 Nazar554 发布,翻译遵循 CC BY-SA 4.0 许可协议

要添加到上面的@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>)
}

原文由 The Aelfinn 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进