社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
用react开发有一段时间了,有一个疑惑,为什么构造函数中需要写super(props)?
第一种情况,假如我们不写会怎么样?
import React, { Component } from "react";
class Text extends Component {
constructor (props) {
// super( );
console.log(props)
console.log( this.props) ;
}
render (){
return null;
}
}
export default Text
我们运行代码,会发现报错了。
Js引擎强制你在调用父类构造函数之前,不允许使用this.这是有很好的理由的。
比如:你需要使用父类里面的属性或者方法时,这种时候是访问不到的。
2:如果我们写了。但是不传递参数,写成super(),会怎样?
import React, { Component } from "react";
class Text extends Component {
constructor (props) {
super( );
console.log(props)
console.log( this.props) ;
}
render (){
return null;
}
}
export default Text
结果·如下:
因为你没有传递props给父类构造函数,所以你在构造函数里面
无法访问this,props,但是你在构造函数外面依然可以!!!
import React, { Component } from "react";
class Text extends Component {
constructor (props) {
super( );
console.log(props)
console.log( this.props) ;
}
componentDidMount () {
console.log(this.props);
}
render (){
return null;
}
}
export default Text
React内部,在构造函数之后,马上又实例了一遍props,因此,即便你忘记了传入props给super,但是React依然在事后会设置它
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!