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

先上代码:

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>
    )
}

难道是接口定义错了吗?

阅读 6k
2 个回答
const Login: React.FC<RouteComponentProps> = ({ history }) => {
    function handleSubmit() {
        history.push('/')
    }
   
    return (
        <div>
            <button onClick={handleSubmit}>登录</button>
        </div>
    )
}
interfacr Props extends RouteComponentProps {
  ...
}

或者

type Props = RouteComponentProps & { ... };

正常情况推荐第一种

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题