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

相关推荐
3824278278 分钟前
python:输出JSON
前端·python·json
2503_9284115614 分钟前
12.22 wxml语法
开发语言·前端·javascript
光影少年30 分钟前
Vue2 Diff和Vue 3 Diff实现及底层原理
前端·javascript·vue.js
2501_9462243134 分钟前
旅行记录应用统计分析 - Cordova & OpenHarmony 混合开发实战
javascript·harmonyos·harvester
傻啦嘿哟38 分钟前
隧道代理“请求监控”实战:动态调整采集策略的完整指南
前端·javascript·vue.js
JIngJaneIL39 分钟前
基于java + vue个人博客系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
C_心欲无痕43 分钟前
vue3 - readonly创建只读的响应式对象
前端·javascript·vue.js
Rabi'1 小时前
编译ATK源码
前端·webpack·node.js
SoaringHeart1 小时前
Flutter组件封装:视频播放组件全局封装
前端·flutter
TAEHENGV1 小时前
进度跟踪模块 Cordova 与 OpenHarmony 混合开发实战
android·javascript·数据库