首页 > 解决方案 > 无法访问道具中的“历史”

问题描述

我有一些 React 组件。

import * as React from 'react';
import { Component } from 'react';
import { FormControl, Button } from 'react-bootstrap';

type Props = {
  history: any[];
};

// How to define Props only once, in base component

class BaseComponent extends Component<Props, State> { 
}

class HomeComponent extends BaseComponent {

  constructor(props: any) {

    super(props);

    this.state = {
      name: ""
    };
  }

  onSubmit = (event: any) => {
      event.preventDefault();
      this.props.history.push('/messenger'); // TYPE ERROR !!!
  }

  render() {
    <FormControl autoFocus value={this.state.name} />  // TYPE ERROR !!!
    <Button type="submit">Enter</Button>
  }
}

当带有组件的文件具有扩展名 .js 时,它可以正常工作,但是如果我将其重命名为 .tsx ,则会出现以下错误。

Property 'history' doesn't exist 
on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'

同样的错误表明状态中不存在“名称”。如何告诉 React 这不是错误?

TS 配置。

{
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "output",
    "module": "esnext",
    "target": "es5",
    "lib": ["es6", "dom"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src"
  },
  "exclude": [
    "node_modules",
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "server"
  ]
}

然后我以这种方式运行项目。

react-scripts-ts start

更新#1

当我从 React.Component 继承它时让它工作,不知道如何创建 CustomBaseComponent,但这可能是另一个问题。

interface IProps {
  history: any[];
}

class HomeComponent extends React.Component<IProps> {

  public state: any = {};

  constructor(props: IProps) {

    super(props);

    this.state = {
      name: ""
    };

    this.props.history.push('/demo'); // now history works as expected
  }
}

更新#2

看起来 React 更喜欢 HTML 组件级别的继承,而不是标准的 JS 类继承。

https://reactjs.org/docs/composition-vs-inheritance.html

标签: reactjstypescript

解决方案


您需要为组件的 props 和 state 定义类型,并将它们指定为类型参数Component

type HomeProps = {
    history: /* insert type here */;
};
type HomeState = {
    name: string;
};

class HomeComponent extends Component<HomeProps, HomeState> {
  // ...
}

推荐阅读