【React源码解析】React源码中的几种关键数据结构

React源码中的几种关键数据结构

element对象

jsx

_jsxs方法就是来生成element对象的,它执行的结果才是element对象

element对象是对UI的描述

https://babeljs.io/ 可以尝试自己玩一下

/*#__PURE__*/ 这个注释可以帮助webpack做tree shaking
function App() {
  return /*#__PURE__*/_jsxs("div", {
    id: "div",
    class: "div",
    children: [/*#__PURE__*/_jsx("span", {}), /*#__PURE__*/_jsx("p", {
      id: "p"
    })]
  });
}

类型声明文件

export interface ReactElementType {
    // 元素类型
    $$typeof: symbol | number;

    type: ElementType;
    // for循环中的key,不加默认用index代替
    key: Key;

    // 组件的props
    props: Props;

    // 组件ref
    ref: Ref;

    // 我们自己的特殊标记
    __mark: string;
}

fiber对象

fiber对象是对react执行过程中元素状态的描述,打上一些标记等等

export class FiberNode {
    // 元素类型,函数式组件就是函数本身
    type: any;   // div span li ul

    // 组件对象类型
    tag: WorkTag;

    // 组件初始props
    pendingProps: Props;
    key: Key;

    // 真实dom
    stateNode: any;
    ref: Ref;

    return: FiberNode | null;
    sibling: FiberNode | null;
    child: FiberNode | null;
    index: number;

    // 更新后的props状态
    memoizedProps: Props | null;
    memoizedState: any;

    // 连体婴儿  双缓存机制
    alternate: FiberNode | null;    

    // 副作用标记
    flags: Flags;
    subtreeFlags: Flags;
    updateQueue: unknown;
    constructor(tag: WorkTag, pendingProps: Props, key: Key) {
        // 实例
        this.tag = tag;
        this.key = key;
        // HostComponent <div> div DOM
        this.stateNode = null;
        // FunctionComponent () => {}
        this.type = null;

        // 构成树状结构
        this.return = null;
        this.sibling = null;
        this.child = null;
        this.index = 0;

        this.ref = null;

        // 作为工作单元
        this.pendingProps = pendingProps;
        this.memoizedProps = null;
        this.memoizedState = null;
        this.updateQueue = null;

        this.alternate = null;

        // 副作用, 更新元素的标记
        this.flags = NoFlags;
        this.subtreeFlags = NoFlags;
    }
}

worktag是对元素类型的进一步抽象

export type WorkTag =
    | typeof FunctionComponent
    | typeof HostRoot
    | typeof HostComponent
    | typeof HostText;

export const FunctionComponent = 0;
export const HostRoot = 3;   // hsotroot代表生成的中间空节点

export const HostComponent = 5;   // 原生节点  div span等
// <div>123</div>
export const HostText = 6;
  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值