React -- react中关于构造函数中super(props)的问题 - Go语言中文社区

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


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

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/wust_cyl/article/details/84947883
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-26 16:05:29
  • 阅读 ( 528 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢