Element 为 Object

784 阅读1分钟

这里要提前说明一下,一般我们定义的组件的type 也就是 element 的type 是 function。 比如:我们定义了App组件,那么App组件生成的 element 的属性 type 是 f App(props)。这些在 前文 element的位置有写。

一般,只要一个组件的 render函数返回的不是null,或者是false的还,这些内容转换为 element 的话,其类型便是 Object。

Element 为 Object

当然 element 的类型为 Object的时候,也要分多钟情况。 一是: element的type属性值为 string。 一是: element的type属性值为 function。 一是: isInternalComponentType(element.type)值为true。

    else if(typeof node == 'object'){
        
        if (typeof element.type === 'string') {
          /*
            ReactNativeComponent.createInternalComponent 方法是被注入进来的,注入的是 ReactDOMComponent 类。
            最终的结构是 new ReactDOMComponent(element.type,element.props)
    
            生成一个 ReactDOMComponent 的实例返回
          */ 
          instance = ReactNativeComponent.createInternalComponent(element);
        } else if (isInternalComponentType(element.type)) {
          // This is temporarily available for custom components that are not string
          // representations. I.e. ART. Once those are updated to use the string
          // representation, we can drop this code path.
          instance = new element.type(element);
        } else {
    
          /*
            是我们自定义的类的时候 执行该方法来进行生成 instance 操作。
          */ 
          instance = new ReactCompositeComponentWrapper();
          
        }
    }
    

前两种情况好理解,关键是第三种情况。

isInternalComponentType

我们先来看看 isInternalComponentType 方法是什么鬼!

type指的是 element的type。 element 的 type 则是在 ReactElement 模块中定义的。

如果 type的类型是 function。 而且 type.prototype 有值。 而且type.prototype 拥有 mountComponent,receiveComponent两个方法。

满足以上的条件,则返回true。

简单的一句话来说是:

该方法的作用是检测 type 的类型是 已知的内部类型,而不是用户提供的复合类型。

这个东西是为以后的版本准备的,这里不会涉及,就先略过。

    function isInternalComponentType(type) {
        return typeof type === 'function' 
        && typeof type.prototype !== 'undefined' 
        && typeof type.prototype.mountComponent === 'function'
        && typeof type.prototype.receiveComponent === 'function';
    }