React类组件中super()和super(props)的区别详解
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
以上就是React类组件中super()和super(props)的区别详解的详细内容,更多关于React super()和super(props)区别的资料请关注脚本之家其它相关文章!
相关文章
react中useState使用:如何实现在当前表格直接更改数据
这篇文章主要介绍了react中useState的使用:如何实现在当前表格直接更改数据,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-08-08
React hook 'useState' is calle
这篇文章主要为大家介绍了React hook 'useState' is called conditionally报错解决,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-12-12
使用react-virtualized实现图片动态高度长列表的问题
一般我们在写react项目中,同时渲染很多dom节点,会造成页面卡顿, 空白的情况。为了解决这个问题,今天小编给大家分享一篇教程关于react-virtualized实现图片动态高度长列表的问题,感兴趣的朋友跟随小编一起看看吧2021-05-05


最新评论