我们都知道,在react父子组件通信中,我们经常会在使用class创建的子组件里写constructor、super,这些相关的api其实是ES的内容并不是react的内容。让我们来重新认识一下吧。
class式写法的父子组件通信示例
import React, { Component } from "react";
// 子组件
class ClsChildren extends Component {
constructor(props) {
// 如果constructor函数里调用this,那么必须先进行super操作;
// 如果constructor函数里需要使用this.props,那么super中必须有props参数
super(props);
this.state = {};
console.log(this.props);
}
render() {
return (
<div style={{ backgroundColor: "#00a2ff", padding: "5px" }}>
<p>我是子组件</p>
<p>{this.props.text}</p>
</div>
);
}
}
// 父组件
export default class ClsParent extends Component {
render() {
return (
<div style={{ backgroundColor: "#00ffa2", padding: "30px" }}>
<p>Parent</p>
<ClsChildren text="这是父组件传递到子组件的值"></ClsChildren>
</div>
);
}
}
当然我们在面试中也经常会遇到关于以下3问:
🌸1.class中使用与不使用constructor构造函数的区别是什么?
constructor是一种用于创建和初始化class
创建的对象的特殊方法。
- ⭐ 当我们不显式指明(不写)
constructor
时,由于组件是继承自React.Component
,所以组件默认构造函数是:
constructor(props, context){ super(props, context); };
所以,尽管组件中并未声明constructor构造函数,却仍然可以直接引用
this.props
- ⭐ 当我们显式指明
constructor
时,此时默认的构造函数被我们指明的constructor
重写,为何需要覆盖默认构造函数呢?因为我们自定义的组件也想要有自己的一些状态,比如我们常见的组件中指明state状态等。
🌸2.定义class组件,为什么需要加上 super() ?
super
的作用:super关键字,它指代父类的实例(即指代父类的this对象),子类没有自己的this对象,而是继承父类的this对象。子类必须在constructor方法中调用super方法,从而得到父类的this对象,否则会报错。说白了,如果想要在constructor构造函数中使用this关键字,就必须使用super函数
🌸3.super()加与不加props的区别究竟在哪里呢?
需要在constructor构造函数内使用this.props则super()中必须添加props参数。
但是super()中不添加props时render中仍然可以继续使用this.props。