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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48138111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:21:17  来源:igfitidea点击:

What TypeScript type should I use to reference the match object in my props?

reactjstypescriptreact-router

提问by Nicolas Blanco

In my React containers/component, which type could I use to reference the matchpart included by React Router DOM?

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

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

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

回答by Nazar554

You don't need to add it explicitly. You can use RouteComponentProps<P>from @types/react-routeras a base interface of your props instead. Pis type of your match params.

您不需要明确添加它。您可以使用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
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;
}

回答by The Aelfinn

To add onto @Nazar554's answer above, the RouteComponentPropstype should be imported from react-router-dom, and implemented as follows.

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

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

interface MatchParams {
    name: string;
}

interface MatchProps extends RouteComponentProps<MatchParams> {
}

Further, to allow for re-usable components, the render()function allows you to pass only what the component needs, rather than the entire RouteComponentProps.

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