React 源码解读

本文深入剖析React组件的本质,从源码角度解读Component类的构造及其实现机制,包括props、context、refs、updater属性和setState、forceUpdate方法。同时,探讨了组件初始化过程,解析React.createElement如何生成ReactElement对象。

一、React组件
一个简单的react组件如下

/*
 * A simple React component
 */
class Hello extends React.Component {
  render() {
    return <div>Hello</div>;
  }
}
console.log(<Hello />)
复制代码

输出组件<Hello />是一个如下所示的对象

输出 <Hello><div>world</div></Hello>
在实际组件应用中我们可以通过 props.children获取包裹在组件中的元素
不难看出我们平时写的组件,就是一个js的对象的嵌套树结构
<Hello />是继承了 React.Component这个类,那么我们首先来看下 React.js的源码,

这里我们可以看到React export出了Component、PureComponent、Fragment等模块。 通过 import {Component, PureComponent} from './ReactBaseClasses'; 知道Component类是通过 ReactBaseClasses.js引入的

function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  this.refs = emptyObject;
  this.updater = updater || ReactNoopUpdateQueue;
}
Component.prototype.isReactComponent = {};
Component.prototype.setState = function(partialState, callback) {
  // ...
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};
Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};
复制代码

Component就是一个拥有props、context、refs、updater属性,setState、forceUpdate方的法构造函数,其中setState接收partialStatecallback两个参数。
二、组件的初始化
通过babel解析Hello组件, 得到render方法实际上是调用了React.createElement方法,我们找到ReactElement这个文件,

createElement方法返回一个ReactElement对象,就是我们之前通过console打印出来的结构。

export function createElement(type, config, children) {
  // ...
  return ReactElement(
    type,
    key,
    ref,
    self,
    source,
    ReactCurrentOwner.current,
    props,
  );
}
复制代码
const ReactElement = function(type, key, ref, self, source, owner, props) {
  const element = {
    // This tag allows us to uniquely identify this as a React Element
    $$typeof: REACT_ELEMENT_TYPE,
    // Built-in properties that belong on the element
    type: type,
    key: key,
    ref: ref,
    props: props,
    // Record the component responsible for creating this element.
    _owner: owner,
  };
  return element;
};
复制代码

因此React组件的实质是通过执行React.createElement创建出来的ReactElement类型的js对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值