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

Reactjs 我应该使用什么类型的脚本来引用道具中的匹配对象?,reactjs,typescript,react-router,Reactjs,Typescript,React Router,在我的React容器/组件中,我可以使用哪种类型来引用React路由器DOM中包含的match部分 interface Props { match: any // <= What could I use here instead of any? } export class ProductContainer extends React.Component<Props> { // ... } 界面道具{ 匹配:任何//您不需要显式添加。您可以使用@types/reac

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

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

export class ProductContainer extends React.Component<Props> {
  // ...
}
界面道具{

匹配:任何//您不需要显式添加。您可以使用
@types/react router
中的
RouteComponentProps
作为您的道具的基本接口。
p
是匹配参数的类型

import { RouteComponentProps } from 'react-router';

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

interface MatchParams {
    name: string;
}

interface Props extends RouteComponentProps<MatchParams> {
}
从“react router”导入{RouteComponentProps};
//示例路线
接口匹配参数{
名称:字符串;
}
接口道具扩展了RouteComponentProps{
}
//来自打字
从“历史”中导入*作为H;
导出接口RouteComponentProps

{ 匹配:匹配

; 地点:H.地点; 历史:H.历史; 静态上下文?:任何; } 导出接口匹配

{ 参数:P; isExact:布尔型; 路径:字符串; url:string; }


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

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

interface MatchParams {
    name: string;
}

interface MatchProps extends RouteComponentProps<MatchParams> {
}

问题是,即使为
匹配创建了一个接口,类型警告仍然存在。下面是对我有效的代码:

接口匹配参数{
firstParam:字符串;
optionalParam?:字符串;
}
导出常量CreditPortfolioDetail:FC=(道具)=>{
const{firstParam,optionalParam}=props.match.params;
// ...
}
简单解决方案

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

const Container = ({ match }: RouteComponentProps<{ showId?: string}>) => {
 const { showId } = match.params?.showId;//in case you need to take params
}
从“react router dom”导入{RouteComponentProps};
常量容器=({match}:RouteComponentProps)=>{
const{showId}=match.params?.showId;//以防需要获取params
}

什么是
H
所指?@KarlRichter问题在于,Typescript希望该组件的每次使用都能通过位置历史记录道具等进行传递。RouteComponentProps应将这些道具作为可选道具。必须使用Partial进行包装。@glstuna感谢您提醒我,使用Partial时会是什么样子?还有OP:请包括您的导入。@LeonardoViada尝试使用
Awesome!很好的补充什么是FC?FCIt的React.FC,它是React.FunctionComponent的类型别名。您的函数实际上是一个FunctionComponent,通过明确声明,您还可以将children属性自动添加到您的pr中ops(类似于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>)
}
import { RouteComponentProps } from "react-router-dom";

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