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

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

问题描述

docs 中学习 React 并遇到了这个例子:>

Learning React from the docs and came across this example:

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

根据 Mozilla,超级允许您在构造函数中使用 this.是否有任何其他原因可以使用独立的 super(我知道 super 也允许您访问父类的方法)但是使用 React 是否还有任何其他用例只是调用super() 本身?

According to Mozilla, super allows you to use this in the constructor. Is there any other reason to use a standalone 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() 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()之前不能允许this的原因是因为this未初始化,如果super()> 没有被调用.然而,即使我们没有使用 this,我们也需要在构造函数中使用 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.)

如果我们必须使用this.props,我们在构造函数内部调用super(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天全站免登陆