1. ES6 category
In ES6, class inheritance is implemented through extends keyword, as follows:
class sup{ constructor(name){ =name; } printName(){ () } } class sub extends sup{ constructor(name,age){ super(name) //super represents the constructor of the parent class =age; } printAge(){ () } } let rui=new sub('rui',21); () //21 () //rui
In the example above, you can see that the parent class is called through the super keyword implementation. Super replaces the parent class's construction function. Using super(name) is equivalent to calling()
If the super keyword is not used in the subclass, an error will be raised
The reason for the error is that the subclass does not have its own this object, it can only inherit this object of the parent class and then process it. Super() inherits this object in the parent class to the subclass. Without the super() subclass, this object cannot be obtained.
If you call this first and then initialize super(), it is also a prohibited behavior
Therefore, in the constructor of a subclass, you must first use super to reference this
2. Class components
In React, class components are implemented based on the es6 specification and inherited. Therefore, if constructor is used, you must write super() to initialize this
At this time, when calling super(), we usually need to pass props as a parameter. If it cannot be passed in, React will also define it in the component instance.
// React internalconst instance = new YourComponent(props); = props;
So whether there is or not, it can be used in render. This is automatically included with React and can be written without writing.
class HelloMessage extends { render(){ return <div>hello {}</div> } }
However, it is not recommended to use super() instead of super(props)Because React will add value after the class component constructor generates an instance, in the case of super, the call is undefined, as follows:
class Button extends { constructor(props){ super() //No props were passed in (props) //{} () //undefined } }
All those passed in props can be accessed normally, ensuring that the constructor has been assigned before the execution is completed, which is more logical
class Button extends { constructor(props){ super(props) / (props) //{} () //{} } }
3. Summary
In React, the class component is based on ES6, so in the constructor, super must be used to call the super procedure. Regardless of whether props are passed in or not, React will assign props to the component instance props property. If super() is called, then it is still undefined between super and the end of the constructor.
This is the end of this article about the difference between super() and super(props) in React. For more related React super() and super(props) content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!