Fe-interview: [react] `super()`和`super(props)`有什么区别?

Created on 16 Jul 2019  ·  6Comments  ·  Source: haizlin/fe-interview

[react] super()super(props)有什么区别?

react

Most helpful comment

react 中的class 是基于es6的规范实现的, 继承是使用extends关键字实现继承的,子类必须在constructor()中调用super() 方法否则新建实例
就会报错,报错的原因是 子类是没有自己的this对象的,它只能继承父类的this对象,然后对其进行加工,而super()就是将父类中的this对象继承给子类的,没有super() 子类就得不到this对象。

如果你使用了constructor就必须写super() 这个是用来初始化this的,可以绑定事件到this上
如果你想要在constructor中使用this.props,就必须给super添加参数 super(props)
注意,无论有没有 constructor,在render中的this.props都是可以使用的,这是react自动附带的
如果没有用到constructor 是可以不写的,react会默认添加一个空的constroctor.

All 6 comments

super() 可以让我们使用this来调用各种东西,
而super(props)可以让我们在this的基础上使用构造函数里面的东西, 或者从父元素那边传过来的一些属性

如果只调用了super(),那么this.propssuper()和构造函数结束之间仍是undefined

class Button extends React.Component {
  constructor(props) {
    super(); // 没有传 props
    console.log(props);      // {}
    console.log(this.props); // undefined 
  }
  // ...
}

react 中的class 是基于es6的规范实现的, 继承是使用extends关键字实现继承的,子类必须在constructor()中调用super() 方法否则新建实例
就会报错,报错的原因是 子类是没有自己的this对象的,它只能继承父类的this对象,然后对其进行加工,而super()就是将父类中的this对象继承给子类的,没有super() 子类就得不到this对象。

如果你使用了constructor就必须写super() 这个是用来初始化this的,可以绑定事件到this上
如果你想要在constructor中使用this.props,就必须给super添加参数 super(props)
注意,无论有没有 constructor,在render中的this.props都是可以使用的,这是react自动附带的
如果没有用到constructor 是可以不写的,react会默认添加一个空的constroctor.

根据es6的规定,子类自己的构造函数中必须调用super,才能获得自己的this;所以只是super()的话,只能够让子类获取自己的this;但是props会是Undefined,如果传递了props给super,那么才会初始化子类自己的props

es6规定了子类中如果使用constructor构造函数,在super调用之前是没有自己的this,调用super用来初始化子类的this,至于在super中传props是为了可以通过this.props的形式访问父组件传过来的props

Was this page helpful?
0 / 5 - 0 ratings