react+typescript 类后面的不设置泛型this.props.match就提示错误

发布于 2022-09-07 22:56:13 字数 817 浏览 15 评论 0

刚学typescript
用ts+react_react-router创建项目在使用react-router的this.props.match时遇到以下问题,希望大神指点:

react+typescript 类后面的不设置泛型this.props.match就提示错误
不存在match属性

在constructor参数设置props类型为IProps也无效.

clipboard.png

    import * as React from 'react'
import './index.less'

interface IProps {
    match?: any
}
export default class Home extends React.Component {
    constructor(props:IProps) {
        super(props)
    }
    public componentDidMount() {
        // react-router match 获取url上的参数
        console.log('url 参数:', this.props.match) 
    }
    public render () {
        return (
            <div className="home-wrap">
                欢迎使用, XXX管理系统
            </div>
        )
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

半夏半凉 2022-09-14 22:56:13

@types/react-router 必须安装
在V4中 你要使用 H5 的跳转的时候需要在 组件中使用 withRouter
在Ts中,你需要在Props接口中继承 RouteComponentProps 这个接口:

interface Props extends RouteComponentProps { }
export default withRouter(Index);

以上组件之后,你便可使用this.props.hoisty.push() js 跳转 和 <Link /> 组件中实现跳转
如果你使用的需要在路由中使用的Parmas参数的话,比就需要在定义一个接口 RouterInfo,
并且修改为一下:

interface RouterInfo {
  id: any
}
interface Props extends RouteComponentProps <RouterInfo >{ }

这样的话你在编译的时候就不会出现出行this.props.match.params.id没有找到Id问题
这里的params 适用于:

<React path='goodsList/:id.html' />
生活了然无味 2022-09-14 22:56:13

肯定要设置泛型的啊,不设置当然报错

栖竹 2022-09-14 22:56:13
export default class Home extends React.Component<RouteComponentProps>{
    ...
}
夏了南城 2022-09-14 22:56:13

正确的写法是这样的:https://blog.kangfenmao.com/p...

痴梦一场 2022-09-14 22:56:13

这样写我感觉会比较好吧

interface IArticleProps extends RouteComponentProps {
  match: {
    isExact: boolean
    params: { id: any }
    path: string
    url: string
  }
}

class Article extends React.Component<IArticleProps> {
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文