簡體   English   中英

如何使用ReactJS和Typescript定義組件實例屬性? 屬性“ var”在類型“ App”上不存在

[英]How to define component instance attributes with ReactJS and Typescript? `Property 'var' does not exist on type 'App'`

作為參考,我正在使用React 16.9.0和Typescript 3.6.3

本教程中 ,他們建議不要在我的react類中定義實例屬性:

只是不要。 將值存儲在組件實例上是這樣的:

 var React = require('react/addons'); class ArbitraryWidget extends React.Component { // ... constructor () { this.derp = 'something'; } handleClick () { this.derp = 'somethingElse'; } render () { var something = this.derp; // ... } } 

這特別糟糕,不僅是因為您打破了在this.state上存儲狀態的明顯慣例,而且還因為更新this.derp時渲染不會自動觸發。

但就我而言,我的類具有不影響Component狀態的屬性,那么,我可以毫無問題地將它們添加為實例屬性。

但是,我沒有指責打字稿在屁股上咬人。 如果安裝Create React App並創建Typescript項目,則可以添加以下最小示例來重現該問題:

import React from 'react';
import './App.css';

interface AppProps {
}

interface AppState {
}

class App extends React.Component<AppProps, AppState>
{
  constructor(props: AppProps) {
    super(props);

    this.var = 10;
    this.state = {
    };
  }

  render() {
    return (
      <div>
        Hi!
      </div>
    )
  }

}

export default App;

這將導致Typescript引發錯誤:

/myfiles/src/App.tsx
TypeScript error in /myfiles/src/App.tsx(15,10):
Property 'var' does not exist on type 'App'.  TS2339

    13 |     super(props);
    14 | 
  > 15 |     this.var = 10;
       |          ^
    16 |     this.state = {
    17 |     };
    18 |   }

添加:

interface AppProps {
  var: any;
}

interface AppState {
  var: any;
}

不起作用,Typescript仍然不了解var是組件的屬性,而不是this.propsthis.state的屬性。


更新

如答案中所建議,我嘗試了以下操作:

private var: number;

但是現在,Typescript引發了另一個錯誤:

Property 'var' is missing in type '{}' but required in type 'Readonly<AppState>'.  TS2741

    18 | 
    19 |     this.var = 10;
  > 20 |     this.state = {
       |     ^
    21 |     };
    22 |   }
    23 | 

如果我刪除this.state = {} ,它仍然會拋出該錯誤:

Property 'var' is missing in type '{}' but required in type 'Readonly<AppProps>'.  TS2741

     5 | import * as serviceWorker from './serviceWorker';
     6 | 
  >  7 | ReactDOM.render(<App />, document.getElementById('root'));
       |                  ^
     8 | 
     9 | // If you want your app to work offline and load faster, you can change
    10 | // unregister() to register() below. Note this comes with some pitfalls.

如果varApp的屬性,則它不是您的propsstate一部分,因此將其添加到AppPropsAppState接口將不會使Typescript識別它。

相反,您實際上應該在您的課程中定義它:

class App extends React.Component<AppProps, AppState>
{
  private var: number;

  constructor(props: AppProps) {
    super(props);

    this.var = 10;
    this.state = {
    };
  }

  render() {
    return (
      <div>
        Hi!
      </div>
    )
  }
}

暫無
暫無

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

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