• 对react构造函数研究--------引用


     1.ES6 语法中,super 指代父类的构造函数,React 里面就是指代 React.Component 的构造函数。

    class Person {
    constructor(name) {
    this.name = name;
    }
    }

    class PolitePerson extends Person {
    constructor(name) {
    this.greetColleagues(); //这是不允许的
    super(name);
    }

    greetColleagues() {
    alert('Good morning folks!');
    alert('My name is ' + this.name + ', nice to meet you!');
    }
    }
    如果允许的话,在 s

    uper() 之前执行了一个 greetColleagues 函数,greetColleagues 函数里用到了 this.name,这时还没执行 super(name),greetColleagues 函数里就获取不到 super 传入的 name 了,此时的 this.name 是 undefined。

    super() 里为什么要传 props?

    执行 super(props) 可以使基类 React.Component 初始化 this.props。

    // React 内部
    class Component {
    constructor(props) {
    this.props = props;
    // ...
    }
    }

    有时候我们不传 props,只执行 super(),或者没有设置 constructor 的情况下,依然可以在组件内使用 this.props,为什么呢?

    其实 React 在组件实例化的时候,马上又给实例设置了一遍 props:

    // React 内部
    const instance = new YourComponent(props);
    instance.props = props;

    那是否意味着我们可以只写 super() 而不用 super(props) 呢?

    不是的。虽然 React 会在组件实例化的时候设置一遍 props,但在 super 调用一直到构造函数结束之前,this.props 依然是未定义的。

    class Button extends React.Component {
    constructor(props) {
    super(); // ? 我们忘了传入 props
    console.log(props); // ✅ {}
    console.log(this.props); // ? undefined
    }
    // ...
    }

    如果这时在构造函数中调用了函数,函数中有 this.props.xxx 这种写法,直接就报错了。

    而用 super(props),则不会报错。

    class Button extends React.Component {
    constructor(props) {
    super(props); // ✅ 我们传了 props
    console.log(props); // ✅ {}
    console.log(this.props); // ✅ {}
    }
    // ...
    }

    所以我们总是推荐使用 super(props) 的写法,即便这是非必要的。

  • 相关阅读:
    Opencv算法运行时间
    markdown转换为html
    jQuery类名添加click方法
    box-sizing 盒子模型不改变大小
    nodejs 发送get 请求 获取博客园文章列表
    6、Python3中的常用正则表达式
    5、Python3打印函数名之__name__属性
    4、reduce函数工具的使用
    3、Python字符编码区分utf-8和utf-8-sig
    9、QT QLineEdit 密码模式
  • 原文地址:https://www.cnblogs.com/zhouyideboke/p/12559696.html
Copyright © 2020-2023  润新知