深入理解JSX

Lyx發表於2022-07-07

What is JSX ?

官方定義:JSXReact.createElement(components, props, ...children) 函式的語法糖

<Mybutton color="blue" shadowSize={2}>
Click Me
</Mybutton>

上方函式會被編譯為下方程式碼:

React.createElement(
  Mybutton,
  {color: 'blue', shadowSize: 2},
  'Click Me'
)

開啟 React 的原始碼,找到 createElement 函式:

function createElement(type, config, children) {
  var propName; // Reserved names are extracted

  var props = {};
  var key = null;
  var ref = null;
  var self = null;
  var source = null;

  if (config != null) {
    if (hasValidRef(config)) {
      ref = config.ref;

      {
        warnIfStringRefCannotBeAutoConverted(config);
      }
    }

    if (hasValidKey(config)) {
      {
        checkKeyStringCoercion(config.key);
      }

      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.

  var childrenLength = arguments.length - 2;

  if (childrenLength === 1) {
    props.children = children;
  } else if (childrenLength > 1) {
    var childArray = Array(childrenLength);

    for (var i = 0; i < childrenLength; i++) {
      childArray[i] = arguments[i + 2];
    }

    {
      if (Object.freeze) {
        Object.freeze(childArray);
      }
    }

    props.children = childArray;
  } // Resolve default props

  if (type && type.defaultProps) {
    var defaultProps = type.defaultProps;

    for (propName in defaultProps) {
      if (props[propName] === undefined) {
        props[propName] = defaultProps[propName];
      }
    }
  }

  {
    if (key || ref) {
      var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;

      if (key) {
        defineKeyPropWarningGetter(props, displayName);
      }

      if (ref) {
        defineRefPropWarningGetter(props, displayName);
      }
    }
  }

  return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}

從原始碼中,我們可以看到 createElement 函式接收三個引數: type(標籤型別)、config(標籤中的屬性)、children(子標籤)

但是,在編寫 JSX 的時候,一個標籤通常會包含多個子標籤,那麼該函式是如何接收這些子標籤呢 ?

我們關注原始碼的這一部分:

  var childrenLength = arguments.length - 2;

  if (childrenLength === 1) {
    props.children = children;
  } else if (childrenLength > 1) {
    var childArray = Array(childrenLength);

    for (var i = 0; i < childrenLength; i++) {
      childArray[i] = arguments[i + 2];
    }

    {
      if (Object.freeze) {
        Object.freeze(childArray);
      }
    }

    props.children = childArray;
  } // Resolve default props

我們知道,arguments 物件中包含有所有引數,那麼 childrenLength 就是排除前兩個引數之外剩餘引數的個數

若 childrenLength 為 1,則只有一個子元素(可以是文字也可以是新的JSX) 若 childrenLength 大於 1,則建立一個長度為 childrenLength 的陣列,利用 for 迴圈將arguments 中的物件新增到陣列中

簡化版 React.createElement

ReactElement 物件定義:

function ReactElement(type, key, props) {
    return {
        $$typeof: Symbol.for('react.element'),
    type,
    key,
    props
    }
}

createElement() 函式實現:

function createElement(type, config, children) {
    const props = {};
  if (config) {
        // 將 config 中的鍵值對新增到 props 中
    for (propName in config) {
      if (hasOwnProperty.call(config, propName)) {
        props[propName] = config[propName];
      }
    }
  }

  const childrenLength = arguments.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[2 + i];
    }
    props.children = childArray;
  }
  
  return ReactElement(type, null, props);
}

當僅有一個 DOM 節點時,呼叫 createElement 函式:

let a = createElement(
  'div',
  {width:'20px', height: '20px'},
)

列印出a,其結果為:

{
  '$$typeof': Symbol(react.element),
  type: 'div',
  key: null,
  props: { width: '20px', height: '20px' }
}

由於並沒有子元素,所以 props 中沒有 children 屬性

當父節點含有多個子節點時:

let a = createElement(
  'div',
  {width:'20px', height: '20px'},
  createElement(
    'p'
  ),
  createElement(
    'a'
  ),
)

列印出a,其結果為:

{
  '$$typeof': Symbol(react.element),
  type: 'div',
  key: null,
  props: { width: '20px', height: '20px', children: [ [Object], [Object] ] }
}

可以看到,當含有多個子元素時,children 以陣列的形式儲存這些子元素。