美文网首页前端开发知识
React中constructor及super

React中constructor及super

作者: 小m_up | 来源:发表于2018-03-01 12:29 被阅读1633次
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,如果不需要,那么写不写效果是一样的

相关文章

网友评论

    本文标题:React中constructor及super

    本文链接:https://www.haomeiwen.com/subject/qsrgxftx.html