class Checkbox extends React.Component {
constructor(props) {
super(props);
this.state = { isOn: true };
}
// ...
}
对于上面的类Checkbox来说,它的super是React.Component
接下来我们依次讨论下列问题:
1.如果不调用super会怎么样
2.调用了super但不传props会怎么样
3.没有constructor时会怎么样
一.如果不调用super,那么constructor中就不能使用this
就像下面的例子
constructor(props){
this.state = {
name : '没调用父级的constructor'
}
}
使用了this报错
React这样做的目的是为了防止,在用到父级的数据时,出现未定义的情况,看下面的例子
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!');
}
}
上面的例子会发现PolitePerson是Person的子类,在它的constructor中先调用了greetColleagues函数,这个函数中访问了this.name,由于父级还未被初始化,值undefined,所以为了防止出现这种情况,React就规定,只有在super被调用之后才可以使用this
二. 调用super时不传props会怎么样
看下面代码
class Button extends React.Component {
constructor(props) {
super(); // ? We forgot to pass props
console.log(props); // ✅ {}
console.log(this.props); // ? undefined
}
}
结果就是this.props的值为undefined,有人可能会说啊,不对呀,我在render或者其它函数里都可以用啊。确实,那是因为React为我们干了一件事情
// Inside React
class Component {
constructor(props) {
this.props = props;
// ...
}
}
在constructor执行完之后,React帮你在实例上添加了props属性,赋值为props,以至于这是可以访问props,如果在super调用时没有传props的话,那么在constructor里用this.props是访问不到props的值的,因为它自己没有的东西会去父级中找
所以为了防止出现一些不必要的错误,React是建议我们加上props的,尽管没有硬性的规定
三. 如果class中没有constructor,React会自动帮我们调用super,并把所有的参数传过去,所以不用担心