【 React 】super()和super(props)有什么区别

相关文章 react 中的 super super(props)

1. 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) //super 代表的是父类的构造函数
        this.age=age;
    }
    printAge(){
        console.log(this.age)
    }
}
let rui=new sub('rui',21);
rui.printAge() //21
rui.printName() //rui

在上面的例子在子中,可以看到通过super关键字实现调用父类,super代替的是父类的构建函数,使用super(name)相当于调sup.prototype.constructor.call(this.name)

如果在子类中不使用super关键字,则会引发报错
报错的原因是 子类没有自己的this对象,它只能继承父类的this对象,然后对其进行加工而super()就是将父类中的this对象继承给子类的,没有super()子类就得不到this对象

如果先调用this ,再初始化super(),同样是禁止的行为
所以在子类的constructor 中 ,必须先用super 才能引用this

2. 类组件

在React中,类组件是基于es6的规范实现的,继承React.Component,因此如果用到constructor就必须写super()才初始化this

这时候,在调用super()的时候,我们一般都需要传入props作为参数,如果传不进去,React内部也会将其定义在组件实例中

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

所以无论有没有constructor,在render中this.props都是可以使用的,这是React自动附带的,是可以不写的

javascript 复制代码
class HelloMessage extends React.Component{
    render(){
        return <div>hello {this.props.name}</div>
    }
}

但是也不建议使用super()代替super(props)

因为在React会在类组件构造函数生成实例后再给this.props附值,所以 不传递props在super的情况下,调用this.props为undefined,情况如下:

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

而传入props的则都能正常访问,确保了this.props在构造函数执行完毕之前已经被赋值,更符合逻辑

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

3. 总结

在React 中,类组件基于ES6,所以在constructor中必须使用super
在调用super过程,无论是否传入props,React内部都会将props赋值给组件实例props属性中,如果调用了super(),那么this.props在super和构造函数结束之间仍然是undefined

相关推荐
子兮曰3 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰3 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万3 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝3 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋3 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁3 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
李少兄3 天前
JavaScript 隐式全局变量解析
javascript
汉堡大王95273 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大3 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师3 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端