![](/img/trans.png)
[英]ReactJS and Typescript useContext - property does not exist on type
[英]ReactJS property timerID does not exist on type Clock
我是react js的新手,目前我正在尝试遵循官方的reactjs文档,并运行一些示例。 最近,我尝试了以下示例: https : //reactjs.org/docs/state-and-lifecycle.html
但是当我把这段代码:
import React from 'react';
import ReactDOM from 'react-dom';
class Clock extends React.Component {
state = {
date: new Date()
};
constructor(props:any) {
super(props);
this.timerID = 0;
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
但是在componentDidMount()函数中,出现此错误:
属性ClockID在Clock类型上不存在
我不确定在这里出了什么问题,我试图在状态声明附近声明timerID,但它会导致其他错误,所以我想知道我在做什么错。 顺便说一句,这是离子框架项目,不确定是否会导致错误。
这些是我对package.json的依赖
"dependencies": {
"@ionic/react": "^4.8.0-rc.0",
"@ionic/react-router": "^4.8.0-rc.0",
"@types/jest": "24.0.11",
"@types/node": "11.11.3",
"@types/react": "^16.9.1",
"@types/react-dom": "^16.8.5",
"@types/react-router": "^5.0.3",
"@types/react-router-dom": "^4.3.1",
"ionicons": "^4.6.2",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-router": "^5.0.1",
"react-router-dom": "^5.0.1",
"react-scripts": "3.1.0",
"typescript": "3.5.3"
},
谢谢
此错误来自打字稿而不是来自React, timerID
在类属性中添加timerID
您将需要使用window.setInterval
而不是单独使用setInterval
,因为它将把它键入为NodeJS.Timeout
class Clock extends React.Component {
timerID: number;
state = {
date: new Date()
};
componentDidMount() {
this.timerID = window.setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
您忘记在构造函数中声明timerID
:
constructor(props:any) {
super(props);
this.timerID = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.