无法访问道具中的“历史记录”

时间:2018-08-05 08:42:23

标签: reactjs typescript

我有一些React组件。

a<<<<<<<<<<<<<<<<<<<
127.0.0.1 - - [05/Aug/2018 11:38:56] "GET /profiles/a HTTP/1.1" 200 -
wtf
None<<<<<<<<<<<<<<<<<<<
127.0.0.1 - - [05/Aug/2018 11:38:56] "GET /profiles/None HTTP/1.1" 404 -

当包含扩展名.js的文件可以正常工作时,但如果将其重命名为.tsx,则会出现以下错误。

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

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

TS配置。

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

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

{
  "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"
  ]
}

更新#1

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

react-scripts-ts start

更新#2

像React一样,它更喜欢HTML组件级别的继承,而不是标准的JS类继承。

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

1 个答案:

答案 0 :(得分:1)

您需要为组件的props定义类型并声明状态,并将其指定为Component的类型参数:

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

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