第一部分--基础--ReactElement

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上。

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
}

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

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

1.type类型,用于判断如何创建节点
2.key和ref这些特殊信息
3.props新的属性内容
4.$$typeof用于确定是否属于ReactElement

这些信息对于后期构建应用的树结构是非常重要的,而React通过提供这种类型的数据,来脱离平台的限制

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值