【React源码分析之一】JSX 转化成JS

我们在开发react 过程中一般都是用JSX, 相当于enhanced JavaScript. 能再JS代码中嵌入HTML. 

JSX是通过Babel翻译成JS代码的, 可以通过这个Babel playground 来看看JSX中的html被翻译成什么JS代码

function comp(){
}


  what
  why

被翻译成

"use strict";

function comp() {}

React.createElement("comp", {
  id: "id",
  key: "key"
}, React.createElement("span", null, "what"), React.createElement("span", null, "why"));

那么我们来看看React.createElement函数做了什么:

export function createElement(type, config, children) {
  let propName;

  // Reserved names are extracted
  const props = {};

  let key = null;
  let ref = null;
  let self = null;
  let source = null;

  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];
      }
    }
  }

  // Children can be more than one argument, and those are transferred onto
  // the newly allocated props object.
  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;
  }

  // Resolve default 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,
  );
}

上述代码做了几件事:

  • 将config中的key, ref, __self, __source提取出来存入key, ref, self, source几个变量中,将其他的attributes存到props对象
  • 将子标签存入props.children中,可能只有一个chid, 也可能是child array
  • type.defaultProps的key-value赋给props,如果props[key] 是 undefined
const ReactElement = function(type, key, ref, self, source, owner, props) {
  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;
};

可以看到ReactElement是一个函数,根据出入的参数,返回一个Object而已.

你可能感兴趣的:(【React源码分析之一】JSX 转化成JS)