类型react typescript上不存在属性



我是打字脚本的新手,有人能告诉我为什么会出现这个错误吗?

类型"App"上不存在属性"interval"。

interface State {
userInput:string[];
secondsPassed:number;
}

class App extends React.Component<any, State>{
state:State = {
userInput:[],
secondsPassed:0
}
startTimer = () => {
this.interval = setInterval( () => {
this.setState(() =>{
return {secondsPassed: this.state.secondsPassed+1}
})
},1000)

}

试试这样的东西:

const interval = setInterval(() => {
this.setState(() =>{
return {secondsPassed: this.state.secondsPassed+1}
})
},1000)

Typescript是一种静态类型化语言。这部分意味着您必须在赋值前声明类的变量。简单地声明interval如下:

class App extends React.Component<any, State>{
interval
state:State = {
userInput:[],
secondsPassed:0
}
startTimer = () => {
this.interval = setInterval( () => {
this.setState(() =>{
return {secondsPassed: this.state.secondsPassed+1}
})
},1000)
}

第一个答案很接近,解决方案如下:

class App extends React.Component<any, State>{
private interval: any ;
state:State = {
userInput:[],
secondsPassed:0
}
startTimer = () => {
this.interval = setInterval( () => {
this.setState(() =>{
return {secondsPassed: this.state.secondsPassed+1}
})
},1000)

}

最新更新