【问题标题】:React Router DOM History Object Causes Typescript ErrorReact Router DOM 历史对象导致 Typescript 错误
【发布时间】:2019-01-07 07:58:18
【问题描述】:

我遇到了一个问题,其中我有一个无状态组件,它从 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; }'.

【问题讨论】:

    标签: reactjs typescript react-router-dom


    【解决方案1】:

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

    【讨论】:

    • 你是正确的马特,这确实解决了错误。但是,我很好奇,您将如何处理SignInForm 组件使用来自ReactComponentProps 的多个道具(即location 道具)但SignInPage 组件只需将history 道具传递给SignInForm?有些东西让我觉得我想将ReactComponentProps 保留在那里,这样我就可以访问SignInForm 中的所有道具,即使我的SignInPage 组件不需要传递每个道具。
    • 但是在运行时,您只能访问SignInPage 实际传递下来的道具。如果您想访问其中的几个,最简单的方法可能是全部传递: const SignInPage = (props: RouteComponentProps) =>

      SignIn

    猜你喜欢
    • 2023-01-12
    • 2021-05-10
    • 2017-12-05
    • 2017-03-20
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 2021-06-21
    • 2019-11-03
    相关资源
    最近更新 更多