react中constructor和super

2020-06-20  本文已影响0人  may505

在react中组件中我们一般会写一下代码

constructor(props) {
  super(props);
  // some code
}

1.我们是否可以不用在自雷中写constructor,不写construction也是可以的,但是要看在那些场景下

class HelloWord extends React.Component{
}
// 等价于
class HelloWord extends React.Component{
    construction(...args){
        super(..args)
    }
}

如果子类没有定义constructor方法,这个方法会被默认添加。也就是说,不管有没有显式定义,任何一个子类都有constructor方法,所以在一些特定的环境下是可以省略的。比如下面这个例子

class ErrorCatch extends React.Component {

  handleClick = () => {
    console.log('hello world');
  };

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>点击</button>
      </div>
    );
  }
}
export default ErrorCatch;

2.如果显示定义了constructor,那么就必须在constructor函数里面调用super(),比如

class Person {
    constructor(name){
        this.name = name
    }
}
class MaySir extends Person{
    constructor(){
        super()
    }
    print() {
        console.log("实例化个人");
    }
}

如果只是显示的定义了constructor,而不调用super(),那么实例化就会失败,比如只定义了constructor,而不调用super()

class Person {
    constructor(name){
        this.name = name
    }
}
class MaySir extends Person{
    constructor(){
        // super()
    }
    print() {
        console.log("实例化个人");
    }
}
const man = new MaySir().print()
image.png

报错的原因是:子类中是没有自己的this对象的,它的this对象只能够继承父类的this对象,然后对其加工包装,而super()就是相当于把父类的中this对象过继给子类。如果没有调用super(),那么子类也就不能够使用this对象了。class继承类(extends)如果显示的定义了constructor必须要调用super(),如果不是extends继承类可以不用调用super().注:并且要把super()调用放在最前面执行。
3. 在react中是否需要写super(props),如果在子组件中使用了props就需要调用super(props),否则在子组件中使用this.props会报错,如果在子组件中不使用this.props,则直接调用super()即可

上一篇 下一篇

猜你喜欢

热点阅读