xiaoxiaosaohuo/Note

从JSX到React Element

Opened this issue · 0 comments

从JSX到React Element

React应用中少不了下面这样的代码。

  const mountNode = document.getElementById("root");
    ReactDOM.render(
        <APP></APP>,
        mountNode,
        function() {}
    );

上面的是JSX语法, JSX为创建元素提供了一种语法糖,babel会帮我们调用 React.createElement对JSX语法进行转换。

createElement

根据给定的类型返回一个ReactElement

createElement(type, config, children)

处理一下 key, ref, defaultProps, 然后将其他的参数和 childrens 放到props对象,最后调用ReactElement。

如果组件有多个层级, babel会根据jsx结构,从子级一层一层调用createElement,并把返回的 reactElement 作为父级的children,形成一棵 React Element Tree。

ReactElement

ReactElement是一个工厂函数,用于创建React element,返回一个对象

比较重要的属性如下

$$typeof: REACT_ELEMENT_TYPE,//用于标识这是个react element
type: type,//元素类型
key: key,
ref: ref,
props: props,

2018-11-16 23 04 54

上图对应的React Element tree 如下
2018-11-16 23 42 13

如果是一个 Class 形式的组件,type从原来的dom标签变成对应的类。

后续渲染部分会对不同类型的Element进行不同的处理。
这部分还是非常简单的。