簡體   English   中英

React JS中類型'Readonly <{}>'上不存在屬性'currentTime'

[英]Property 'currentTime' does not exists on type 'Readonly<{}>' in react js

我試圖在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;

強文本

我懷疑您忘記為您的狀態聲明接口。

interface SomeProps {
    otherProps: string
}
interface SomeState {
    currentTime: string
}
class App extends React.Component<SomeProps,SomeState>{
//...
}

現在,狀態被描述為一個空對象,如下所示:

class App extends React.Component<{},{}>

缺少接口,打字稿不知道會發生什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM