【问题标题】:How to access routeProps (history, match, location) from a route-rendered component using react-router-dom in Typescript?如何在 Typescript 中使用 react-router-dom 从路由渲染组件访问 routeProps(历史、匹配、位置)?
【发布时间】:2020-12-17 11:32:54
【问题描述】:

我正在尝试使用 react-router-dom 和 Typescript。

我已经安装了@types/react-router-dom

但我在渲染的组件中找不到routePropshistorymatchlocation

我的意思是,我知道它们存在,但 Typescript 不知道它们。

这就是我渲染这条路线的方式:

我看到herehere 你应该安装@types/react-router。它是否正确?这可能是我在路由渲染组件中没有看到routeProps 的原因吗?

更新:

我已经安装了@types/react-router,但仍然无法从渲染组件访问这些道具。

【问题讨论】:

    标签: reactjs typescript react-router react-router-dom


    【解决方案1】:

    这就是我能够访问<Route/> 渲染组件内的routePropshistorymatchlocation)的方式:

    import React from "react";
    import HomePage from "./HomePage";
    import { RouteComponentProps } from "react-router-dom";
    
    // NEEDS TO EXTEND YOUR PROPS TO ADD RouteComponentProps from @types/react-router-dom
    
    interface HomeContainer extends RouteComponentProps {
    }
    
    const HomeContainer: React.FC<HomeContainer> = (props) => {
      console.log("Rendering HomeContainer...");
    
      props.
    
      return(
        <HomePage/>
      );
    };
    
    export default HomeContainer;
    

    现在可以从props 对象访问historymatchlocation

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 2021-03-10
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2019-04-28
      • 2017-08-31
      • 1970-01-01
      相关资源
      最近更新 更多