在React中,render执行的结果获得的并非真正的DOM节点,结果仅仅是轻量级的JavaScript对象,咱们称之为virtual DOM。
<ul id='list'> <li class='item'>Item 1</li> <li class='item'>Item 2</li> </ul>
{ tagName: 'ul', props: { id: 'list' }, children: [ {tagName: 'li', props: {class: 'item'}, children: ["Item 1"]}, {tagName: 'li', props: {class: 'item'}, children: ["Item 2"]}, ] }
class Tab extends React.Component { render() { React.createElement( 'p', { className: 'class'}, 'Hello React' ) } }
function createElement(type, config, children) { let propName; const props = {}; let key = null; let ref = null; let self = null; let source = null; if (config != null) { if (hasValidRef(config)) { // 若是有ref,将它取出来 ref = config.ref; } if (hasValidKey(config)) { // 若是有key,将它取出来 key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; for (propName in config) { if ( hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName) ) { // 将除ref,key等这些特殊的属性放到新的props对象里 props[propName] = config[propName]; } } } // 获取子元素 const childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { const childArray = Array(childrenLength); for (let i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // 添加默认props if (type && type.defaultProps) { const defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } return ReactElement( type, key, ref, self, source, ReactCurrentOwner.current, props, ); } const ReactElement = function(type, key, ref, self, source, owner, props) { // 最终获得的React元素 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; };
DOM管理历史阶段:前端
“积跬步、行千里”—— 持续更新中~,喜欢留下个赞哦!
往期经典好文:算法
相关专栏推荐:segmentfault