React主要Api 实现原理(一)

React.createElement

当我们书写jsx时其实babel会对其进行转换,如

<App id='firstH'>1</App> 
// 会被编译为
// React.createElement("h1", {
//   id: "firstH"// }, "1")复制代码

其中createElement接受三个参数(type,config,children)

export function createElement(type, config, children) {
...
    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)
            ){
                props[propName] = config[propName]; //将保留的属性去除后放入props对象中
            }
        }
    }
...
    const childrenLength  =  argunments.length - 2 //去除前两个参数 获取children个数
    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
    }

...
    const ReactElement  = function(type, key, ref, self, source, owner, props){
        const element = {
            $$typeof: REACT_ELEMENT_TYPE,
            type: type,
            key: key,
            ref: ref,
            props: props,
            _owner: owner,
        };

        return element;
    }
 ...
}复制代码

其中<App />为ReactElement React元素,App则是React Component React组件

React.Component

下面来看Component的实现
function Component(props, context, updater){
    this.props = props;
    this.context = context;
    this.refs = emptyObject;
    this.updater = updater || ReactNoopUpdateQueue;
}

Component.prototype.isReactComponent = {}; // 标识自己的组件类型
Component.prototype.setState = function(partiacal, callback){ // 进行state设置
    this.updater.enqueueSetState(this, partialState, callback, 'setState'); 
}  // updater 在react-dom包中
Component.prototype.forceUpdate = function(callback){
    this.updater.enqueueForceUpadte(this, callback, 'forceUpdate');}复制代码


猜你喜欢

转载自blog.csdn.net/weixin_33850015/article/details/91379394