使用TypeScript写React,如何使用React-router-dom相关的api

发布于 2022-09-12 00:25:41 字数 1373 浏览 14 评论 0

先上代码:

import { RouteComponentProps } from 'react-router-dom'

const Login: React.FC<any> = ({ history }: RouteComponentProps) => {
    function handleSubmit() {
        history.push('/')
    }
   
    return (
        <div>
            <button onClick={handleSubmit}>登录</button>
        </div>
    )
}

上面的代码是能够正常工作的,但是使用了any,不是很好。所以我定义了一个接口:

import { RouteComponentProps } from 'react-router-dom'

interface Props {
  history: RouteComponentProps
}

const Login: React.FC<Props> = (props) => {
    function handleSubmit() {
        props.history.push('/')
    }
   
    return (
        <div>
            <button onClick={handleSubmit}>登录</button>
        </div>
    )
}

这样写了之后就报错了,ts的提示:Property 'push' does not exist on type 'RouteComponentProps<{}, StaticContext, any>'

我换成这样的写法也是提示同样的错误:

import { RouteComponentProps } from 'react-router-dom'

interface Props {
  history: RouteComponentProps
}

const Login: React.FC<Props> = ({ history }) => {
    function handleSubmit() {
        history.push('/')
    }
   
    return (
        <div>
            <button onClick={handleSubmit}>登录</button>
        </div>
    )
}

难道是接口定义错了吗?

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

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

发布评论

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

评论(2

冰之心 2022-09-19 00:25:41
const Login: React.FC<RouteComponentProps> = ({ history }) => {
    function handleSubmit() {
        history.push('/')
    }
   
    return (
        <div>
            <button onClick={handleSubmit}>登录</button>
        </div>
    )
}
烦人精 2022-09-19 00:25:41
interfacr Props extends RouteComponentProps {
  ...
}

或者

type Props = RouteComponentProps & { ... };

正常情况推荐第一种

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