React类组件中super()和super(props)有什么区别?

React中super()和super(props)有什么区别?

回答思路:说说ES6类的继承-->说说类组件的继承-->总结区别

ES6类的继承

在ES6中,通过extends关键字实现类的继承,如下:

javascript 复制代码
class sup{
	constructor(name){
		this.name = name;
	}
	printName(){
		console.log(this.name);
	}
}
class sub extends sup{
	constructor(name,age){
		super(name);
		this.age = age;
	}
	printAge(){
		console.log(this.age);
	}
}	
let tom = new sub("tom",20);
tom.printName(); //tom
tom.printAge(); //20

通过super关键字实现调用父类,super代替父类的构建函数,相当于调用sup.prototype.constructor.call(this,name),如果子类不适用super关键字会报错,报错的原因是子类没有自己的this对象,他只是继承父类的this对象,然后对其加工,也不能先用this,再调用super

类组件的继承

类组件继承React.Component,因此如果用到constructor就必须写super(),才能初始化this,在调用super的时候一般要传入props作为参数,如果不传进去,react内部也会将其定义在组件实例中

javascript 复制代码
// react内部
const instance = new ExampleComponent(props);
instance.props = props;

所以无论有没有constructor,在render中的this.props都是可以使用的,在react中,使用super(),不传入props,调用this.props为undefined,如下:

javascript 复制代码
class Button extends React.Component{
	constructor(props){
		super(); 
		console.log(this.props); //undefined
	}
}

如果传入props:

javascript 复制代码
class Button extends React.Component{
	constructor(props){
		super(props);
		console.log(this.props); //{}
	}
}

总结区别

不管是super()还是super(props),React内部都会将props赋值给组件实例props属性中,如果只调用super(),那么在构造函数结束之前,使用this.props还是undefined

相关推荐
自进化Agent智能体3 分钟前
Hermes 工具与工具集——Hermes 的内置能力
javascript
用户29307509766915 分钟前
TypeScript 必考题:Type 与 Interface 全面对比
前端
hunterandroid24 分钟前
[鸿蒙从零到一] HarmonyOS 媒体能力实战:图片、音频与视频处理
前端
打呵欠的猫27 分钟前
我让 AI 封装了一个 ImageUpload 组件,它设计的 5 层校验链路比我想的周全
前端·ai编程
AlexMaybeBot29 分钟前
躺在沙发上开发 Openclaw 的移动端APP
前端·flutter
用户21816970493030 分钟前
Flutter(十三)Text Image TextField
前端
程序员黑豆35 分钟前
深入解析Java数据类型:基本类型与引用类型的本质区别与实战选择
前端·ai编程·全栈
你挚爱的强哥36 分钟前
【exportExcel】单纯靠js不用任何其他第三方插件导出xls格式文件
开发语言·javascript·ecmascript
东方小月2 小时前
从零开发一个 Coding Agent(七):实现纯文本 Agent Loop
前端·人工智能
大家的林语冰2 小时前
👉 尤雨溪再次成立新公司,同时官宣 Pinia 4 正式发布!
前端·javascript·vue.js