exportfunctioncreateElement(type, config, children) { let propName; const props = {}; let key = null; let ref = null; let self = null; let source = null;
// 在这段if代码中,createElement将config中传入的一些参数, // 也就是翻译之前类html标签中的那些组件属性(html attribute)过滤了一下,传入了props中, // 过滤的依据就是,属性值是否是在保留属性列表中,保留属性共有四个:key、ref、__self、__source if (config != null) { if (hasValidRef(config)) { ref = config.ref; } if (hasValidKey(config)) { key = '' + config.key; }
self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if ( hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName) ) { props[propName] = config[propName]; } } }
// 下面的这段代码是判断标签的子标签,并且构造一个子标签的数组。 // 此处,react构造标签(组件,以后都称为组件)的时候并不是通过一个数组进行的,而是通过传入多个参数的方法,通过javascript中提供的arguments属性来获取额外的子组件。 const childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } elseif (childrenLength > 1) { const childArray = Array(childrenLength); for (let i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } if (__DEV__) { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; }
// 为组件添加默认的一些属性 if (type && type.defaultProps) { const defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (__DEV__) { if (key || ref) { const displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } // 最终,通过构造上述传入的一系列的参数,返回一个构造号的ReactElement组件 returnReactElement( type, key, ref, self, source, ReactCurrentOwner.current, props, ); }
ReactElement包含的内容
ReactElement实则为一个方法,返回了一个element对象,具体如下:
1 2 3 4 5 6 7 8 9 10 11
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, };