如何在TypeScript中声明react-router参数

awj*_*awj 10 typescript reactjs react-router

我正在尝试使用Typescript以一种接受参数的方式设置react-router.

在我的render元素中我有

<Route path="/show/:id" component={TestComp} />
Run Code Online (Sandbox Code Playgroud)

我定义TestComp

const TestComp = ({ match }) => (
    <div>
        <h2>Showing specified ID: {match.params.id}</h2>
    </div>
)
Run Code Online (Sandbox Code Playgroud)

但是,VS Code强调了match参数(在声明中TestComp)并告诉我

绑定元素'match'隐式具有'any'类型.

它无法编译.

任何人都可以告诉我match应该声明什么类型?我已经尝试RouteProps但是这也不起作用.查看index.d.ts,我认为它被定义为match<P>但我不确定如何将参数声明为泛型类型.

更新
基于对@ TarasPolovyi的回答的评论,我添加了以下内容:

在此输入图像描述

如您所见,这仍然存在问题.

Mah*_*uva 11

如果您使用的是react-routerv4,则RouteComponentProps从中导入react-router-dom并使用type RouteComponentProps<RouteInfo>- 参数名称必须匹配


Raf*_*aeu 8

如果您使用的是 Typescript 和 React Router V 4.0,则语法会有所不同。您声明您的路线如下:

<Route path="/home/:topic?" render={() => {
   return this.renderView(<ContentHolder />);
}} />
Run Code Online (Sandbox Code Playgroud)

然后组件声明如下:

interface RouteInfo {
    topic: string;
}

interface ComponentProps extends RouteComponentProps<RouteInfo> {
}

class ContentHolder extends Component<ComponentProps> {

    render() {
        return (
            <Content>
                <h1 className="page-title">{this.props.match.params.topic}</h1>
            </Content>
        );
    };
};

export default withRouter(ContentHolder);
Run Code Online (Sandbox Code Playgroud)

然后在您的内部,您this.props.match.params将在 VS Code 和 IntelliJ 中获得完全的 IntelliSense


Geo*_*mov 6

首先,你需要导入matchreact-router-dom

这是我从create react应用程序生成的代码的副本:

import {
    BrowserRouter as Router,
    Route,
    Link,
    match
} from 'react-router-dom';
Run Code Online (Sandbox Code Playgroud)

您需要这样的接口:

interface Identifiable {id: string; }
Run Code Online (Sandbox Code Playgroud)

match是您需要的东西。像这样:

const TestComp = (mathedRoute: match<Identifiable>) => (
    <div>
        <h2>Showing specified ID: {mathedRoute.params.id}</h2>
    </div>
)
Run Code Online (Sandbox Code Playgroud)


小智 1

您应该安装一个包@types/react-router,其中具有react-router. 它包含一个接口match<P>,因此您可以使用它来描述您的属性类型。