在 React 类组件 中,constructor 构造函数里调用 super(props) 是一个非常经典的机制,
一、基本背景
在 React 中,我们定义类组件时通常这样写:
class MyComponent extends React.Component {constructor(props) {super(props); // ✅ 关键点this.state = { count: 0 };}render() {return <div>{this.props.name} - {this.state.count}</div>;}
}
二、为什么要调用 super(props)?
因为 MyComponent 是继承自 React.Component 的类。
在 JavaScript 的类继承机制中,子类必须在使用 this 之前调用 super()。
super() 的作用就是调用父类(即 React.Component)的构造函数。
如果不调用它,你的组件实例还没有被正确初始化。
三、为什么传入 props?
super(props) 会把 props 传递给父类的构造函数,这样:
-
React 才能在 constructor 中通过 this.props 访问到属性;
-
否则 this.props 会是 undefined。
示例对比:
constructor(props) {super(); // ❌ 没传 propsconsole.log(this.props); // undefined
}constructor(props) {super(props); // ✅ 传入 propsconsole.log(this.props); // 正常输出传入的 props
}
四、总结一句话
目的 | 解释 |
---|---|
调用 super() |
初始化父类(React.Component)实例 |
传入 props |
让 this.props 在构造函数中可用 |
必须在使用 this 前调用 |
否则会抛出错误 “Must call super constructor in derived class before accessing 'this'” |