react的constructor和super的具体含义和使用

1.constructor( )-----super( )的基本含义
这是ES6对类的默认方法,通过 new 命令生成对象实例时自动调用该方法。并且,该方法是类中必须有的,如果没有显示定义,则会默认添加空的constructor( )方法。
super( ) ——继承
      在class方法中,继承是使用 extends 关键字来实现的。

    子类 必须 在 constructor( )调用 super( )方法,否则新建实例时会报错。

     报错的原因是:子类是没有自己的 this 对象的,它只能继承自父类的 this 对象,然后对其进行加工,而super( )就是将父类中的this对象继承给子类的。没有 super,子类就得不到 this 对象。

2.super(props)------super()-----以及不写super的区别
(1).如果你用到了constructor就必须写super(),是用来初始化this的,可以绑定事件到this上;
(2).如果你在constructor中要使用this.props,就必须给super加参数:super(props);
(3).(无论有没有constructor,在render中this.props都是可以使用的,这是React自动附带的;);

(4).如果没用到constructor,是可以不写的.React会默认添加一个空的constructor。
Box.js

class Box extends Component{
constructor(){
super();
this.state = {
text: '',
id: 'q3dfa',
image: 'https://www.baidu.com/img/xinshouye_034fec51df225fe8410f36ad3f2fccf6.png'
}
}
render(){
console.log('box render');
let {text, id, image} = this.state;
return (
<div className="box">
<One path={image}/>
<Two content={text} id={id}/>
<button onClick={()=>{this.setState({id: 'fd4sd'})}}>修改</button>
<input type="text" value={text} onChange={this.inputChange.bind(this)}/>
</div>
)
// return React.createElement('div', {className: 'box'}, 'hello');
}


原文地址:https://www.cnblogs.com/yunshangwuyou/p/9497817.html