【发布时间】:2025-11-25 01:10:01
【问题描述】:
我知道这个问题被问了很多次,但仍然不清楚。 刚才很多人说:
如果你想在那里访问
this.props,请将 props 传递给构造函数
one more example of the answer
官方文档说 Class components should always call the base constructor with props. ,但如果我们不将 props 传递给 constructor,我们仍然会在除构造函数之外的任何地方都有 this.props。
同样从react source code我们可以看到 React.Component 的源代码
function ReactComponent(props, context) {
this.props = props;
this.context = context;
}
但这让我更加困惑。
super() 应该使用两个参数调用:props 和 context。但是我们调用了我们的 super empty 并且仍然可以访问两个this.props。
根据 ECMA 文档 super() 调用父 constructor() 并将参数传递给 super() 。但是我们的super() 是空的。
所以我的问题是:
- 为什么官方文档说:
类组件应始终使用 props 调用基本构造函数。
- 如果
super()和constructor()为空,React 如何将props设置为子组件? - 是不是 React 特性的 bug,在子组件中可以访问 props 而无需将 props 传递给
super()和constructor()?
【问题讨论】:
-
妥协:
constructor(...args) { super(...args); } -
你为什么要查看这些过时的源代码?
-
github.com/facebook/react/blob/master/packages/react/src/…:
createElement添加props,无论您是否使用super(props)。 -
@Li357 感谢新源代码的链接。那么当前的 React 文档是错误的还是什么?不需要总是用
props打电话给constructor吗? -
抱歉,有人知道答案吗?
标签: javascript reactjs ecmascript-6 es6-class