React中constructor及super

constructor( )

Reactconstructor表示父类的构造方法,用来新建父类的this对象,这是ES6对类的默认方法,该方法是类中必须有的,如果没有显示定义,则会默认添加空的constructor( )方法。

class Point {
}

// 相当于
class Point {
  constructor() {}
}

super( )

class方法中,继承使用 extends 关键字来实现。子类 必须 在 constructor( )调用 super( )方法,否则新建实例时会报错,因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工,如果不调用super方法;子类就得不到this对象。

super

super
很明显自动就报错了,所以只要有constructor就必须有super
super or super(props)
先看个例子:
class Main extends React.Component {
    constructor() {
        super();
        this.state = {count: 1};
    }

    render() {
        return (
            <div>
                {this.state.count}
                <App count={this.state.count}/>
            </div>
        );
    }
}

class App extends React.Component {
    constructor() { //没有写props
        super();
    }

    render() {
        return (
            <div>
                {this.props.count}
            </div>
        );
    }
}

运行后显示正确,当在constructorsuper中写了props,也毫无影响,运行显示正确,那么将App组件中的constructor改为:

constructor() {
    super();
    this.state = {c: this.props.count};
}
<div>
       {this.state.c}
</div>
那么报错如下:
当把App组件中的constructor改为:
constructor(props) {
    super(props);
    this.state = {c: this.props.count};
 }
那么运行显示正确

所以说super()super(props)的区别就是你是否需要在构造函数内使用this.props,如果需要那么你就必须要写props,如果不需要,那么写不写效果是一样的

共有 0 条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据