Thanks to visit codestin.com
Credit goes to github.com

Skip to content

React内部原理,第二部分: componentWillMount and componentDidMount #2

@forthealllight

Description

@forthealllight

React内部原理,第二部分: componentWillMount and componentDidMount


第一部分我们在Feact中实现了一个基础的渲染,实现了一个最重要的生命周期函数render,在本部分中,我们会为组件添加两个生命周期函数componentWillMount和componentDidMount.

这一系列的文章包括:

  • 第一部分:基础渲染
  • 第二部分:componentWillMount and componentDidMount
  • 第三部分:基础更新
  • 第四部分:setState
  • 第三部分:transaction

修改createClass方法

在之间的createClass方法中,仅仅支持render方法,比如:

const Feact = {
    createClass(spec) {
        function Constructor(props) {
            this.props = props;
        }

        // 只使用了构造对象中的render属性,而没有用其他的属性
        Constructor.prototype.render = spec.render;

        return Constructor;
    }
}

我们仅仅需要一个简单的方式,就可以将spec中的其他方法添加到Constructor.prototype中,这样在createClass方式创建的组件不仅可以有render函数,还可以实现其他用户自定义的函数。

const Feact = {
    createClass(spec) {
        function Constructor(props) {
            this.props = props;
        }

        Constructor.prototype =
            Object.assign(Constructor.prototype, spec);

        return Constructor;
    }
    ...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions