Home > Web Front-end > Front-end Q&A > Can super be used in react?

Can super be used in react?

WBOY
Release: 2022-06-27 16:09:55
Original
1363 people have browsed it

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)".

Can super be used in react?

The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.

Using super in react

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]); 
// 调用 父对象/父类 上的方法
Copy after login

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();
Copy after login

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.

Can super be used in react?

Can super be used in react?

## 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 constructor

3. React currently supports a new writing method. The initialization data below without constructor is very convenient

Can super be used in react?

[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template