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中设置。
| 归档时间: |
|
| 查看次数: |
11217 次 |
| 最近记录: |