React Element
React Element是一个简单的对象(plain object),描述了组件实例或DOM节点以及它们所需的属性,用于告诉React你想要渲染什么。
React Element是一个不可变的描述性对象,element对象上没有任何方法,它有两个主要的属性:type和props。
React Element相互嵌套组合可以构成一颗树(也就是Virtual DOM)。当调用ReactDOM.render或setState时,会置顶向下解析这颗树,这个解析的过程是调和过程(reconciliation)的一部分。当reconciliation完成后,会得到新的Virtual DOM,最终使用react-dom中的渲染器(renderer)进行最小更新渲染。
element的分类
DOM Element:type是string。(DOM Element是React中最小的单位)
123456789101112{type: 'button',props: {className: 'button button-blue',children: {type: 'b',props: {children: 'OK!'}}}}Component Element:type是React中的函数或类
1234567{type: Button,props: {color: 'blue',children: 'OK!'}}
Reconciliation
Reconciliation是置顶向下的
当一个element的type是函数或者类,他会将props属性传入函数或类得到一个新的element,依次执行下去,直到element是DOM element(type是string)
源码解读: ReactElement.js
定义了一个工厂函数,用于创建ReactElement
createElement(type, config, children)
type的值可以是:a tag name string, a React component type, a React fragment type。示例如下:
可以通过config设置props的值,config上的属性会覆盖type的defaultProps。props上不会有内置属性:key、ref等
createElement可以接收3个或更多参数。除了type和config,其他的参数都会作为children。如下props.children的值可以是 单个element,也可以是 element数组
可以通过config设置element的属性:key、ref
cloneElement(element, config, children)
等价于<element.type {...element.props} {...props}>{children}</element.type>
可以通过config重写key、ref。当重写ref后,要修改_owner
isValidElement(object)
ReactElement是一个简单对象,并且它的symbol是Symbol.for('react.element')