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

相关推荐
好雨知时节t几秒前
sleep 函数在React项目中的运用
javascript
好雨知时节t几秒前
关于Scheduler 类,一个并发控制调度器
javascript
xw-busy-code4 分钟前
Prettier 学习笔记
javascript·笔记·学习·prettier
毕设源码-郭学长10 分钟前
【开题答辩全过程】以 基于Web的网上问诊系统的设计与实现为例,包含答辩的问题和答案
前端
电商API&Tina10 分钟前
电商数据采集API接口||合规优先、稳定高效、数据精准
java·javascript·数据库·python·json
酉鬼女又兒43 分钟前
零基础快速入门前端DOM 操作核心知识与实战解析(完整汇总版)(可用于备赛蓝桥杯Web应用开发)
开发语言·前端·javascript·职场和发展·蓝桥杯·js
喝拿铁写前端1 小时前
一套面向 Web、H5、小程序与 Flutter 的多端一致性技术方案
前端·架构
yaaakaaang2 小时前
(一)前端,如此简单!---下载Nginx
前端·nginx
牛奶2 小时前
为什么全国人民都能秒开同一个视频?
前端·http·cdn
KongHen022 小时前
uniapp-x实现自定义tabbar
前端·javascript·uni-app·unix