super(props)对我的React组件有什么作用? [英] What is super(props) doing for my React component?
问题描述
我不太喜欢JS,也不喜欢React.
I am not great with JS and playing around with React.
位于此处的React文档指出以下内容:
The React docs located here state the following:
在实现
React.Component
子类的构造函数时,您可以应该在其他任何语句之前调用super(props)
.除此以外,this.props
将在构造函数中未定义,这可能导致错误.
When implementing the constructor for a
React.Component
subclass, you should callsuper(props)
before any other statement. Otherwise,this.props
will be undefined in the constructor, which can lead to bugs.
我的问题是,这实际上如何工作? super()
的作用是什么在我的构造函数中神奇地启用了 this.props
?
My question is HOW does this actually work? What is super()
doing that magically enables this.props
within my constructor?
推荐答案
在您提到的文档中.它是用javascript的ES6标准编码的.
In the documentation that you have mentioned. It is coded in ES6 standard of javascript.
所以这句话
class Greeting extends React.Component
这意味着Greeting是从 React.Component
继承的,通过调用 super
,您实际上是在使用 props
参数
It means Greeting is inherting from React.Component
, by calling super
, you are actually calling the parent element with props
parameter,
如果您打算在 constructor
中使用 this.props
,则必须调用 super(props)
if you intend on using this.props
inside the constructor
, you have to call super(props)
希望这些链接很有帮助.
这篇关于super(props)对我的React组件有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!