本文主要介绍 react 的基础知识点,包括 React 如何从 jsx 转换为 fiber 结点,再生成最后的 dom 结构,以及对 fiber 节点生成过程进行详细的描述。图文比较多,请耐心阅读。
知识点概览
React element
在编写 react 组件时,大家都会使用 jsx 语法,如下:
const Component = () => {
const list = [1, 2, 3];
return (
<ul>
{list.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
};
jsx 模板,会在 react 项目打包构建的时候,通过 babel 转译为一个 React.createElement 的函数调用。
const Component = () => {
const list = [1, 2, 3];
return React.createElement(
"ul",
null,
list.map((item) => React.createElement("li", { key: item }, item))
);
};
当 Component 组件函数被调用时,会执行 React.createElement 方法,返回一个称为 react element 的 AST 对象。
{
$$typeof: Symbol(react.element),
key: null,
ref: null,
type: 'ul',
props: {
children: [{
$$typeof: Symbol(react.element),
key: 1,
ref: null,
type: 'li',
props: { children: 1},
...
}, {
$$typeof: Symbol(react.element),
key: 2,
ref: null,
type: 'li',
props: { children: 1},
...
}, {
$$typeof: Symbol(react.element),
key: 3,
ref: null,
type: 'li',
props: { children: 1 },
...
}]
},
...
}
AST, 全称 Abstract Syntax Tree,学名抽象语法树,简称语法树,是源代码语法结构的一种抽象表示。在 react 中, react element 作为 AST,是 jsx 模板抽象出来的树形数据结构,在 react 工作过程中起到了非常重要的作用。
从 jsx 到 dom 结构
当 React 执行时,会把 template 转为具体的 DOM 结构
从 template 到 dom 结构,中间经历的主要过程如下
其中,fiber tree 是上述整个过程的核心部分。 fiber tree 和 dom tree 中间存在映射关系,两颗 tree 的相关节点会一一对应。 当 fiber tree 结构发生变化时,dom tree 也会相应的更新变化。
从 react element 到 fiber tree
我们通过一个比较简单的示例来说明一下 react element 是如何转化为一颗 fiber tree。
首先是一个结构比较简单的 react element:
{
type: "A";
props: {
children: [
{
type: "B",
props: {
children: [
{
type: "e",
props: {},
},
],
},
},
{
type: "C",
props: {
children: [
{
type: "F",
props: {},
},
{
type: "G",
props: {},
},
],
},
},
{
type: "D",
props: {},
},
];
}
}
通过 react element 创建 fiber tree 的过程,我们通过下面图解来说明:
总结
结合上面图解,我们做一个总结:
fiber tree 中存在三种类型的指针
child
、sibling
、return
。其中,child
指向第一个子节点,sibling
指向兄弟节点,return
指针指向父节点;fiber tree 采用的深度优先遍历,如果节点有子节点,先遍历子节点;子节点遍历结束以后,再遍历兄弟节点;没有子节点、兄弟节点,就返回父节点,遍历父节点的兄弟节点;
当节点的
return
指针返回 null 时,fiber tree 的遍历结束;
参考资料
https://juejin.cn/post/7007622432013942798#heading-12
如有侵权请告知340443366@qq.com,侵权必删