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

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

ES6类的继承

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

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内部也会将其定义在组件实例中

// react内部
const instance = new ExampleComponent(props);
instance.props = props;

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

class Button extends React.Component{
   
	constructor(props){
   
		super(); 
		console.log(this.props); //undefined
	}
}

如果传入props:

class Button extends React.Component{
   
	constructor(props){
   
		super(props);
		console.log(this.props); //{}
	}
}

总结区别

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

相关推荐

  1. Reactsuper()super(props)什么区别

    2024-01-21 07:54:02       59 阅读
  2. Reactsuper()super(props)什么区别

    2024-01-21 07:54:02       45 阅读
  3. react18,useState useEffect什么区别

    2024-01-21 07:54:02       50 阅读
  4. Reactstateprops什么区别

    2024-01-21 07:54:02       39 阅读
  5. React 】stateprops什么区别

    2024-01-21 07:54:02       37 阅读
  6. ReactVue什么区别

    2024-01-21 07:54:02       32 阅读
  7. 虚拟DOM是什么以及React Vue区别

    2024-01-21 07:54:02       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-21 07:54:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-21 07:54:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-21 07:54:02       82 阅读
  4. Python语言-面向对象

    2024-01-21 07:54:02       91 阅读

热门阅读

  1. 机器学习-决策树

    2024-01-21 07:54:02       42 阅读
  2. 63 C++ 多线程 timed_mutex,recursive_timed_mutex

    2024-01-21 07:54:02       48 阅读
  3. 深入理解Spring框架中Bean的作用域与生命周期

    2024-01-21 07:54:02       61 阅读
  4. vue2自定义封装图片预览组件

    2024-01-21 07:54:02       54 阅读