React Router DOM 历史对象导致 Typescript 错误

React Router DOM History Object Causes Typescript Error

我遇到了一个问题,我有一个无状态组件,该组件从 react-router-dom 传递 History 对象并通过道具将该对象传递给有状态对象。 Typescript 似乎不认为我可以将历史对象作为道具传递下去。

这是我的组件

import { History } from 'history';
import * as React from 'react';
import { RouteComponentProps, withRouter } from 'react-router-dom';

const SignInPage = ({ history }: { history: History }) =>
  <div>
    <h1>SignIn</h1>
    <SignInForm history={history} />
  </div>

class SignInForm extends React.Component<RouteComponentProps<{}>, {}> {

  constructor(props: RouteComponentProps<{}>) {
    super(props);
  }

  public handleClick = () => {
    const { history } = this.props;
    history.push('/home')
  };

  public render() {

    return (
      <button onClick={this.handleClick}>Sign In!</button>
    );
  }
}

export default withRouter(SignInPage);

export { SignInForm };

我得到的错误是这样的。

Type '{ history: History; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<SignInForm> & Readonly<{ children?: ReactNode; }> ...'.
  Type '{ history: History; }' is not assignable to type 'Readonly<RouteComponentProps<{}, StaticContext>>'.
    Property 'location' is missing in type '{ history: History; }'.

我从未使用过 React Router,但如果我正确理解类型,通过声明 SignInForm extends React.Component<RouteComponentProps<{}>, {}>,你是说 SignInForm 需要 all路由组件在被 React Router 调用时通常接收的 props。由于您自己调用它并仅传递历史记录,因此您应该将其声明为 SignInForm extends React.Component<{history: History}, {}>.