为什么react类组件中需要在 constructor 的 super 函数中传递 props

178 阅读1分钟

什么是constructor

constructor是es6中的class里的一个默认方法,在每次执行new的时候会执行这个方法,如果没有显式的声明这个方法,会默认传入一个空的方法。该方法默认返回this即这个初始化的对象

class Test {
    constructor() {
        console.log("haha")
        this.test = true
    }
}
const test = new Test() // haha
console.log(test) // Test {test:true}

super关键词

super关键字可以被当作对象或者函数使用,在进行子类执行的时候,必须使用该关键词一次,否则会报错。此方法会调用父类构造函数,返回子类实例。

class Father {}
class Son extends Father {
    constrctor() {
        super()
    }
}

React类组件使用

下述创建了一个Test的构造函数继承至React.Component。

import React, { Component } from "react";

class Test extends Component {
    constructor() {
        super();
        console.log(this.props); // undefined
    }
    render() {
        return (
            <div>
                test
            </div>
        );
    }
}

使用

import React, { Component } from "react";
import Test from "./Test"
class App extends Component {
    render() {
        return (
            <div>
                <Test type="我是传入的props"/>
            </div>
        );
    }
}

页面中正常展示,但是在子组件中的this.props打印出来的是undefined。为了可以正常打印,我们需要在super里传入props参数,这是为什么呢。

constructor(props) {
    super(props);
    console.log(this.props); // {type:"我是传入的props"}
}

Component的初始化

function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  this.refs = emptyObject;
  this.updater = updater || ReactNoopUpdateQueue;
}

Component在初始化的时候,类组件会在实例上绑定 props 和 context ,初始化置空 refs 属性。所以我们在super中没有传入props,在初始化的时候props为undefined,所以当我们在子组件constructor中打印为undefind

结束语

每天学习一点点,每天懂一点点