在React构造函数中调用super()有什么作用? [英] What does calling super() in a React constructor do?

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

问题描述

文档学习反应,并遇到了这个示例:

Learning React from the docs and came across this example:

class Square extends React.Component {
  constructor() {
    super();
    this.state = {
      value: null,
    };
  }
  ...
}

根据 Mozilla ,super允许你使用构造函数中的。是否有任何其他原因使用独立超级(我知道 super 允许您访问父类的方法)但是React是否有任何其他用例只能单独调用 super()

According to Mozilla, super allows you to use this in the constructor. Is there any other reason to use a stand alone super (I know super allows you to access parent class's methods as well) but with React is there any other use case of just calling super() by itself?

推荐答案

super()只有在具有构造函数的情况下才会在react组件中调用。例如,下面的代码不需要super:

super() is called inside a react component only if it has a constructor. For example, the below code doesn't require super:

class App extends React.component {
    render(){
        return <div>Hello { this.props.world }</div>;
    }
}

但是如果我们有一个构造函数那么 super()是强制性的:

However if we have a constructor then super() is mandatory:

class App extends React.component {
    constructor(){
        console.log(this) //Error: 'this' is not allowed before super()

    }
}

super之前不允许的原因( )是因为如果未调用 super(),则未初始化。但是即使我们没有使用这个,我们在构造函数中需要一个 super(),因为 ES6类构造函数必须调用super,如果它们是子类。因此,只要你有一个构造函数,就必须调用 super()。 (但是子类不必有构造函数)。

The reason why this cannot be allowed before super() is because this is uninitialized if super() is not called. However even if we are not using this we need a super() inside a constructor because ES6 class constructors MUST call super if they are subclasses. Thus, you have to call super() as long as you have a constructor. (But a subclass does not have to have a constructor).

我们在构造函数中调用 super(props)如果我们必须使用 this.props ,例如:

We call super(props) inside the constructor if we have to use this.props, for example:

class App extends React.component{
    constructor(props){
        super(props);
        console.log(this.props); // prints out whatever is inside props

    }
}

我希望我能说清楚。

这篇关于在React构造函数中调用super()有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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