在我的React容器/组件中,我可以使用哪种类型来引用match
React Router DOM包含的部分?
interface Props {
match: any // <= What could I use here instead of any?
}
export class ProductContainer extends React.Component<Props> {
// ...
}
在我的React容器/组件中,我可以使用哪种类型来引用match
React Router DOM包含的部分?
interface Props {
match: any // <= What could I use here instead of any?
}
export class ProductContainer extends React.Component<Props> {
// ...
}
Answers:
您无需显式添加。您可以改用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;
}
import * as H from 'history';
要添加到上述@ 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>)
}
H
指什么?