Super can be used in react; the constructor defined in react must call super() to initialize the parent class. super() can call the constructor of the parent class to instantiate the subclass itself. If To use "this.props" in the constructor, you must add parameters to super, and the syntax is "super(props)".
The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.
When learning react, there is a super (props) in the constructor. What does it mean specifically.
The super syntax comes from es6, and its syntax is as follows:
super([arguments]); // 调用 父对象/父类 的构造函数 super.functionOnParent([arguments]); // 调用 父对象/父类 上的方法
If we want to understand super (props) in react, let’s first take a look at the constructor constructor of es6
Look at the following js
class Person{ constructor(props){ console.log("参数:"+props); console.log("初始化 Person constructor"); this.name = "Person"; } } class Child extends Person{ getName(){ console.log("名字为:"+this.name); } } var child = new Child(); child.getName();
In js, when a class is instantiated with new, the system will call the constructor function by default. In the Child class, we do not define a constructor, and the system will have a constructor by default, and Super() will be called inside; After we define the constructor, we will use what we defined. Therefore, the constructor we define must call super() to initialize the parent class.
In react, if you don’t need to use props in the constructor, you don’t need to write the constructor.
## This The difference between calling and not calling, 1. If you don’t need to use this.props in the constructor, you don’t need to pass props to super. 2. If you don’t want to write logic in the constructor , just write a super (props), in fact there is no need to write the entire constructor3. React currently supports a new writing method. The initialization data below without constructor is very convenient [Related recommendations:javascript video tutorial, web front-end】
The above is the detailed content of Can super be used in react?. For more information, please follow other related articles on the PHP Chinese website!