【问题标题】:What is the purpose of using super in extension of a React.Component? [duplicate]在 React.Component 的扩展中使用 super 的目的是什么? [复制]
【发布时间】:2016-12-24 18:28:52
【问题描述】:

为什么你需要在下面的例子中拥有超级?它实际上从 React.Component 中获取了它需要对 props 做什么?如果您已经从 React.Component 扩展了 CommentList,为什么非常必要 - 传递给构造函数的道具不会像传递给 React.Component 一样被执行吗?

class CommentList extends React.Component {
  constructor(props) {
    super(props);
    this.state = { comments: [] }
  } ...
}

【问题讨论】:

    标签: javascript reactjs super


    【解决方案1】:

    这是一个关于继承的面向对象编程 (OOP) 概念。

    类可以从父类继承方法和属性(在您的情况下,CommentList 继承自 React.Component [因此关键字 extends])

    但是,当您为新类命名同名的方法时,父类的方法会被覆盖。

    这个想法也适用于构造函数(即在实例化时运行的方法)。

    根据 OOP 的性质,当您在 CommentList 上声明构造函数时,您会覆盖 React.Component 的构造函数方法。

    因此,您需要调用 super() 以确保父级的构造函数也使用道具。 (因此超级(道具))。

    【讨论】:

      【解决方案2】:
      class CommentList extends React.Component {
        constructor(props) {
          console.log(this) // Error
        } 
      }
      

      this 直到 super() 被调用后才被初始化

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-17
        • 1970-01-01
        • 2016-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-31
        相关资源
        最近更新 更多