处理前的代码
import React, { useState } from 'react';
class LetAntconst extends React.Component {
timerID: NodeJS.Timer | undefined;
constructor(props) {
super(props);
this.state = {
date: new Date().toLocaleString(),
};
this.showTime = this.showTime.bind(this);
this.clertTime = this.clertTime.bind(this);
}
componentDidMount(): void {
this.timerID = setInterval(() => {
this.tick();
}, 1000);
}
clertTime() {
clearInterval(this.timerID);
}
showTime(name: string): void {
console.log(name);
this.timerID = setInterval(() => {
this.tick();
}, 1000);
}
tick() {
this.setState({
date: new Date().toLocaleString(),
});
}
render() {
return (
<div>
{<h1>{this.state.date}</h1>}
<button onClick={this.clertTime}>停止</button>
<button onClick={this.showTime.bind(this, '启动')}>启动</button>
</div>
);
}
}
export default LetAntconst;
处理后的代码
import React, { useState } from 'react';
type PropType = {
date: string | undefined;
};
type StateType = {
date: string | undefined;
};
class LetAntconst extends React.Component<PropType, StateType> {
timerID: NodeJS.Timer | undefined;
constructor(props: PropType | Readonly<PropType>) {
super(props);
this.state = {
date: new Date().toLocaleString(),
};
this.showTime = this.showTime.bind(this);
this.clertTime = this.clertTime.bind(this);
}
componentDidMount(): void {
this.timerID = setInterval(() => {
this.tick();
}, 1000);
}
clertTime() {
clearInterval(this.timerID);
}
showTime(name: string): void {
console.log(name);
this.timerID = setInterval(() => {
this.tick();
}, 1000);
}
tick() {
this.setState({
date: new Date().toLocaleString(),
});
}
render() {
return (
<div>
{<h1>{this.state.date}</h1>}
<button onClick={this.clertTime}>停止</button>
<button onClick={this.showTime.bind(this, '启动')}>启动</button>
</div>
);
}
}
export default LetAntconst;
解决方法有两种
这个是typeScript报错如上加上类型就可 (推荐)
直接React.Component<any, any>报错也会消失(不推荐)
class LetAntconst extends React.Component<any, any>