constructor( )
在React
中constructor
表示父类的构造方法,用来新建父类的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>
);
}
}
运行后显示正确,当在constructor
和super
中写了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
,如果不需要,那么写不写效果是一样的