React——constructor&super

React中constructor和super

constructor构造函数在组件中是否必须

constructor构造函数并不是不可缺少的,子组件可以在一些情况下略去。
根据ES6可知,不论子类是否添加constructor,这个方法在子类缺失constructor的情况下都会默认被添加,在子类new实例的过程都会补上constructor。

constructor和super的关系

子类可以不写constructor,但是一旦写了,就要在constructor中将super()一起写了。
这时组件才能有自己的this,在组件的全局中都可以使用this关键字。如果只添加了constructor,但是不执行super,之后使用的this都是错的

super中是否必须写入参数props

不一定。
当想在constructor中使用this.props的时候,super括号中需要加入props,此时用props也行,用this.props也行。如果在constructor生命周期中不使用this.props或者props时,可以不传入props。总之,super中props是否存在,只影响constructor这一个生命周期能否使用this.props,其他生命周期已经默认存在this.props了。

参考文献

react组件中的constructor和super小知识

猜你喜欢

转载自blog.csdn.net/weixin_40641530/article/details/108078933