React Router DOM历史记录对象导致打字稿错误

时间:2018-07-31 02:23:12

标签: reactjs typescript react-router-dom

我遇到一个问题,我有一个无状态组件,该组件从react-router-dom传递了History对象,然后通过props将该对象向下传递给有状态对象。 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; }'.

1 个答案:

答案 0 :(得分:2)

我从没使用过React Router,但如果我正确理解了键入,则通过声明SignInForm extends React.Component<RouteComponentProps<{}>, {}>来表示SignInForm需要 all 一条路线的道具组件通常在由React Router调用时接收。由于您是自己调用它并仅传递历史记录,因此您只需将其声明为SignInForm extends React.Component<{history: History}, {}>