Next Js & Typescript - 类型示例中不存在属性 setState

Cou*_*ntD 4 javascript typescript reactjs babeljs nextjs

代码工作正常,但我不知道如何在 VSCode 中删除此错误。感谢帮助。

import * as React from 'react';

interface State {
  text: string;
}
export default class Example extends React.Component<State> {
 state: State = {
    text: 'SOME TEXT'
}

private handleChange = () => {
    this.setState({text: 'New Text'}); //error: property setState does not exist on type Example
}

public render(){
    return(
        <div>
        <h2 onClick={this.handleChange}>{this.state.text}</h2>
        </div>
    )
 }
}
Run Code Online (Sandbox Code Playgroud)

kin*_*aro 8

首先,确保你安装了 react 类型定义:

npm install @types/react @types/react-dom
Run Code Online (Sandbox Code Playgroud)

其次,状态的泛型排在第二位,而不是第一位。第一个是道具。

export default class Example extends React.Component<{}, State> {
Run Code Online (Sandbox Code Playgroud)

查看 React 类型定义以验证这一点(转到定义Component)。<P, S>意味着道具,然后状态。

class Component<P, S> {
Run Code Online (Sandbox Code Playgroud)

  • 解决了。添加 npm install @types/react @types/react-dom 谢谢老兄。 (3认同)

小智 7

我在 VSCode 中解决了同样的问题,只需更改使用的打字稿版本=>打开命令面板>“选择打字稿版本”>“使用工作区版本”