super() 上的打字稿错误:预期有 1-2 个参数,但得到了 0

Pos*_*Guy 10 javascript typescript reactjs

我不知道我需要做什么来解决这个 TS 错误:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

declare const Ink: any;

export default class TableOfContents extends Component <{ id: string }, { rendered: boolean }> {
    constructor() {
        super();
        this.state = { rendered: false };
    }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

更新

我觉得放在这里不太好,应该放什么? 在此输入图像描述

Aje*_*hah 13

React 组件的构造函数在安装之前被调用。当实现子类的构造函数时,您应该在任何其他语句之前React.Component调用。super(props)否则, this.props将在构造函数中未定义,这可能会导致错误。

https://reactjs.org/docs/react-component.html#constructor

所以,你需要写:

constructor(props) {
  super(props);
  this.state = { rendered: false };
}
Run Code Online (Sandbox Code Playgroud)

您还可以为 props 和 state 定义接口,以修复所有 TS 警告和更好的智能感知:

interface IProps {
  id: string
}

interface IState {
  rendered: boolean
}

export default class TableOfContents extends Component<IProps, IState> {
  constructor(props: IProps) {
    super(props)
    this.state = {
      rendered: false,
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您的编辑器抱怨并且不接受隐式any,您可以在tsconfig文件中的compilerOptions"noImplicitAny": false中设置。