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)
首先,确保你安装了 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)