我正在尝试在render()中使用状态变量'currentTime',当我这样做时,我被错误提示:“ Readonly <{}>类型上不存在属性'currentTime'” '“
export class App extends React.Component {
constructor(props:any){
super(props);
this.state = {
currentTime:(new Date()).toLocaleString()
}**strong text**
}
public setit()
{
this.setState(
{
currentTime:(new Date()).toLocaleString()
}
)
}
public render()
{
return (
<div className="App">
<h1>Value:{this.state.currentTime}</h1>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
{this.props.children} <code>src/App.tsx</code> and save to reload.
</p>`enter code here`
<input type="button" value="Press" onClick ={this.popup}/>
</div>
);
}
private popup() : any
{
alert("i");
}
}
export default App;
强文本
答案 0 :(得分:2)
我怀疑您忘记为您的状态声明接口。
interface SomeProps {
otherProps: string
}
interface SomeState {
currentTime: string
}
class App extends React.Component<SomeProps,SomeState>{
//...
}
现在状态被描述为一个空对象,如下所示:
class App extends React.Component<{},{}>
缺少接口,打字稿不知道会发生什么。