
super() 和 super(props) 的区别主要在于它们使用的上下文和目的。在 JavaScript 类(特别是在 React 组件类中)中,super() 调用父类的构造函数,而 props 参数通常与 React 组件相关。让我们详细看看这两种用法。
- super() 在普通的 JavaScript 类继承中,super() 用于调用父类的构造函数。这是必须的,因为在子类的构造函数中,如果你想要访问 this 属性,你必须先调用父类的构造函数。否则,this 可能未定义或行为异常。 javascript复制代码class Parent { constructor(name) { this.name = name; }} class Child extends Parent { constructor(name, age) { super(name); // 调用父类的构造函数 this.age = age; }} const child = new Child('Alice', 10);console.log(child.name); // 输出: Aliceconsole.log(child.age); // 输出: 10
- super(props)
在 React 组件类中,super(props) 通常用于在子组件的构造函数中调用父类(即 React.Component)的构造函数,并将 props 传递给它。这是因为 React 组件的构造函数需要初始化 props 和 state,而 super(props) 确保父类的构造函数被正确调用,使得 this.props 在子类的构造函数中可用。
javascript复制代码import React, { Component } from 'react'; class MyComponent extends Component { constructor(props) { super(props); // 调用父类的构造函数并传递 props this.state = { someState: false, }; } render() { return ( {this.props.someProp}); }} 在这个例子中,super(props) 确保 this.props 在 MyComponent 的构造函数中是可用的。如果不调用 super(props),尝试访问 this.props 将会导致错误,因为 this 可能还未被正确初始化。 总结
super() 在普通的类继承中调用父类的构造函数,不需要参数(除非父类构造函数定义了参数)。 super(props) 在 React 组件类中调用父类(React.Component)的构造函数,并传递 props,确保 this.props 在子类的构造函数中可用。
这两者的区别主要在于它们使用的上下文:一个是普通的类继承,另一个是 React 组件类继承。
学在每日,进无止境!更多精彩内容请关注微信公众号。

原文出处:
内容由AI生成仅供参考,请勿使用于商业用途。如若转载请注明原文及出处。
出处地址:http://www.07sucai.com/tech/416.html
版权声明:本文来源地址若非本站均为转载,若侵害到您的权利,请及时联系我们,我们会在第一时间进行处理。