React -- react中关于构造函数中super(props)的问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wust_cyl/article/details/84947883

用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依然在事后会设置它

猜你喜欢

转载自blog.csdn.net/wust_cyl/article/details/84947883