小编典典

在React构造函数中调用super()有什么作用?

reactjs

文档中学习React
并遇到以下示例:

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

根据Mozilla的说法,super允许您this在构造函数中使用。是否有其他原因可以单独使用super(我知道super也可以访问父类的方法),但是使用React时,是否还有其他仅super()通过自身调用的用例?


阅读 1025

收藏
2020-07-22

共1个答案

小编典典

super()仅在具有构造函数的React组件内部被调用。例如,以下代码不需要超级:

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

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

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

    }
}

之所以this不能被允许之前的原因super()是因为thissuper()调用if未初始化。但是,即使不使用,this我们也需要super()内部构造函数,因为ES6 class constructors MUST call super if they are subclasses。因此,super()只要有构造函数,就必须调用。(但是子类不必具有构造函数)。

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

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

    }
}

我希望我能说清楚。

2020-07-22