react源码学习

2.2

1.react中组件首字母要大写,否则react会把它作为一个html标签对待
babel处理前的源码:

<Div></Div>
<div></div>

babel处理后的代码

React.createElement(Div, null);
React.createElement("div", null);

2.3

1、ReactElement通过createElement创建,调用该方法需要传入三个参数:
type
config
children

type指代这个ReactElement的类型

字符串比如div,p代表原生DOM,称为HostComponent
Class类型是我们继承自Component或者PureComponent的组件,称为ClassComponent,方法就是functional Component
原生提供的Fragment、AsyncMode等是Symbol,会被特殊处理
TODO: 是否有其他的

从源码可以看出虽然创建的时候都是通过config传入的,但是key和ref不会跟其他config中的变量一起被处理,而是单独作为变量出现在ReactElement上。

在最后创建ReactElement我们看到了这么一个变量$$typeof,这是个啥呢,在这里可以看出来他是一个常量:REACT_ELEMENT_TYPE,但有一个特例:ReactDOM.createPortal的时候是REACT_PORTAL_TYPE,不过他不是通过createElement创建的,所以他应该也不属于ReactElement

ReactElement只是一个用来承载信息的容器,他会告诉后续的操作这个节点的以下信息:

type类型,用于判断如何创建节点
key和ref这些特殊信息
props新的属性内容
$$typeof用于确定是否属于ReactElement
这些信息对于后期构建应用的树结构是非常重要的,而React通过提供这种类型的数据,来脱离平台的限制


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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值