Open SUNYIMIN opened 4 years ago
1.在es6的语法中, super()代表的是父类的构造函数,在react中就代表的是React.Component的构造函数 在执行super()之前,你不能在构造函数中使用this,js不允许这么使用,为什么不允许
class Person { constructor(name) { this.name = name; } } class PolitePerson extends Person { constructor(name) { this.greetColleagues(); //这是不允许的 super(name); } greetColleagues() { alert('Good morning folks!'); alert('My name is ' + this.name + ', nice to meet you!'); }
在这种情况下this.name 不存在
super中为什么要传props,主要值初始化父类的this.props, 继承父类的props属性,使子类可以使用this.props
class Component { constructor(props) { this.props = props; // ... }
1.在es6的语法中, super()代表的是父类的构造函数,在react中就代表的是React.Component的构造函数 在执行super()之前,你不能在构造函数中使用this,js不允许这么使用,为什么不允许
在这种情况下this.name 不存在