在我的React容器/组件中,我可以使用哪种类型来引用React Router DOM包含的match
部分?
interface Props {
match: any // <= What could I use here instead of any?
}
export class ProductContainer extends React.Component<Props> {
// ...
}
答案 0 :(得分:64)
您无需明确添加。您可以使用RouteComponentProps<P>
中的@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;
}
答案 1 :(得分:4)
简单的解决方案
import { RouteComponentProps } from "react-router-dom";
const Container = ({ match }: RouteComponentProps<{ showId?: string}>) => {
const { showId } = match.params?.showId;//in case you need to take params
}
答案 2 :(得分:3)
要添加到上述@ Nazar554的答案中,应从RouteComponentProps
导入react-router-dom
类型,并按如下方式使用。
import {BrowserRouter as Router, Route, RouteComponentProps } from 'react-router-dom';
interface MatchParams {
name: string;
}
interface Props 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>)
}
答案 3 :(得分:1)
问题是,即使在为 match<Params>
创建接口之后,类型警告仍然存在。这是对我有用的代码:
interface MatchParams {
firstParam: string;
optionalParam?: string;
}
export const CreditPortfolioDetail: FC<RouteComponentProps<MatchParams>> = (props) => {
const { firstParam, optionalParam} = props.match.params;
// ...
}