在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