【问题标题】:Angle brackets containing interface in class declaration类声明中包含接口的尖括号
【发布时间】:2020-04-25 16:19:38
【问题描述】:

我正在学习打字稿,我正在学习本教程:https://blog.alexdevero.com/react-and-typescript-pt3/

当他谈到界面时,他会以以下方式使用它:

// Create interface for class component props
interface PropsInterface {
  heading: string;
}

// Create interface for class component state
interface StateInterface {
  firstName: string;
  lastName: string;
}

class MyApp extends React.Component<PropsInterface, StateInterface> {

// This state annotation is optional
  // it is for better type inference
  state: StateInterface = {
    firstName: 'Andrew',
    lastName: 'Coboll'
  }

  render() {
    return (
      <div>
        {this.props.heading} {this.state.firstName} {this.state.lastName}
      </div>
    )
  }
}

包含接口的尖括号是什么意思?

最好的问候

【问题讨论】:

    标签: reactjs typescript class interface


    【解决方案1】:

    表示你的props对象的类型是PropsInterface,你的状态对象的类型是StateInterface。这样做你就不需要这样做了。

     state: StateInterface = {
        firstName: 'Andrew',
        lastName: 'Coboll'
      }
    

    你可以这样使用:

     state = {
        firstName: 'Andrew',
        lastName: 'Coboll'
      }
    

    当您在尖括号中添加类型时,它已经知道您所在州的类型

    【讨论】:

      【解决方案2】:

      贴出来后我就明白了,所以在这里分享一下:

      我读过的所有帖子都说要在https://www.typescriptlang.org/docs/handbook/generics.html 上看到通用。

      我阅读了文档,但我无法理解,因为现在我创建的不是泛型类,而是 Component 类。

      所以我希望 Component 类在概念上是这样声明的:

      class Component<P, S>{
          props: P;
          state: S
      }
      

      所以当我创建一个扩展组件的类时,我用尖括号设置接口

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-19
        • 1970-01-01
        • 2021-02-02
        • 2010-10-21
        • 2013-07-30
        • 2014-09-06
        • 1970-01-01
        相关资源
        最近更新 更多