# **react组件中的constructor和super小知识**
1、react中用class申明的类一些小知识
如上图:类Child是通过class关键字申明,并且继承于类React。
A、Child的类型是? typeof Child === 'function' , 其实就相当于ES5用function申明的构造函数 function Child() { //申明构造函数 }
B、Child类调用时候( new Child() ),会优先执行,并且自动执行Child的constructor函数。
3、Child类中的this? this指向Child的实例,相当于 new Child() 那么它们完全相等吗? 不是的,react中的this是在new Child()基础上进行了包裹
结论:this是在new Child()基础上进行了包裹,包含了一些react内部方法,
同时组件中使用Child类( <div> <Child /> </div> ),可以看成 new Child() + react包裹。
import React from "react"
import ReactDom from "react-dom"
export default class DataBind extends Component{
constructor(){
// super
可以不写constructor,一旦写了constructor,就必须在此函数中写super(),
此时组件才有自己的this,在组件的全局中都可以使用this关键字,
否则如果只是constructor 而不执行 super() 那么以后的this都是错的!!!
super()
this.state=({
value:"react的数据双向绑定"
})
handle(e){
this.setState=({
value: e.target.value
})
}
}
return({
<div style={{color:"blue"}}>
// 用bind改变this的指向
<input value="this.state.value" onChange="this.handle.bind(this)" />
</div>
})
}
分享一下
继承
ES5的继承,实质是先创造子类的实例对象的this,然后再将父类的方法添加到this(Parent.apply(this)).
ES6的继承机制完全不同,实质是先创造父类的实例this(所以必须先调用super方法),然后再用子类的构造函数修改this。
如果子类没有定义constructor方法,这个方法会默认添加,代码如下,不管有没有显示定义,任何一个子类都有constructor方法
class ColorPoint extends Point {
}
// 等同于
class ColorPoint extends Point {
constructor(…args) {
super(…args);
}
}// 可见没有写constructor,在执行过程中会自动补上
由ES6的继承规则得知,不管子类写不写constructor,在new实例的过程都会给补上constructor。
所以:constructor钩子函数并不是不可缺少的,子组件可以在一些情况略去。