super(props)对我的React组件有什么作用? [英] What is super(props) doing for my React component?

查看:51
本文介绍了super(props)对我的React组件有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太喜欢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 call super(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆