React 源码阅读 - JSX 最终变成了什么

1,193 阅读2分钟

JSX

相信大家在看到 React 源码的时候,可能或多或少都会有一些疑惑,到底从哪里开始看呢?

我打算以 JSX 作为起点,因为刚开始学写 React 代码的时候,也是从 JSX 开始的。

JSX 编译成了什么

首先,我们要知道浏览器肯定是无法识别 .jsx 这种格式的文件的,它在运行之前会被编译成 .js 文件。以下面这段代码为例:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <h3>Hello, Eagle!</h3>,
  document.getElementById('root')
);

我们可以去 babel 上编译一下上面这段代码:

import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render( /*#__PURE__*/React.createElement("h3", null, "Hello, Eagle!"), document.getElementById('root'));

我们平时编译的时候就是通过 @babel/plugin-transform-react-jsx 插件显式告诉 Babel 编译时需要将 JSX 编译为什么函数的调用(默认为 React.createElement )。当然我们也可以添加一个注解,来告诉 Babel 编译为什么函数,比如下面这个例子:

/** @jsx h */
function App() {
	return <h3>Hello, Eagle!</h3>
}

编译后:

/** @jsx h */
function App() {
  return h("h3", null, "Hello, Eagle!");
}

React.createElement

从上面的代码可以看出 .jsx 文件中的元素全都被编译成了以 React.createElement 函数来创建的形式,由此可以推测,React.createElement 函数的作用应该就是 React 创建自己供内部使用的一个类似于 DOM 树的对象。

React.createElement 函数的源码在 packages/react/src/ReactElement.js

/**
 * 根据 type 创建并返回一个新的 ReactElement.
 * See https://reactjs.org/docs/react-api.html#createelement
 * @param {*} type 标签类型
 * @param {*} config 属性
 * @param {*} children 子元素
 * @returns ReactElement 
 */
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;
  
  // config 不为空的时候需要对其进行校验并赋值给 props 对象
  if (config != null) {
    if (hasValidRef(config)) {
      ref = config.ref;

      if (__DEV__) {
        warnIfStringRefCannotBeAutoConverted(config);
      }
    }
    if (hasValidKey(config)) {
      key = '' + config.key;
    }

    self = config.__self === undefined ? null : config.__self;
    source = config.__source === undefined ? null : config.__source;
    // 处理完一些特殊属性,剩下的属性都放入到一个新的 props 对象
    for (propName in config) {
      if (
        hasOwnProperty.call(config, propName) &&
        !RESERVED_PROPS.hasOwnProperty(propName)
      ) {
        props[propName] = config[propName];
      }
    }
  }

  // children 可能有多个,他们会被赋值到 props 对象的 children 属性上
  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];
    }
    // 防止有人篡改核心对象
    if (__DEV__) {
      if (Object.freeze) {
        Object.freeze(childArray);
      }
    }
    props.children = childArray;
  }

  // 处理 defaultProps
  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 方式返回一个包含组件数据的对象
  return ReactElement(
    type,
    key,
    ref,
    self,
    source,
    ReactCurrentOwner.current,
    props,
  );
}

ReactElement

React.createElement 函数返回的对象都是 ReactElement,是一个对象。

const ReactElement = function(type, key, ref, self, source, owner, props) {
  const element = {
    // 这是 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,
  };

  if (__DEV__) {
    // 省略
  }

  return element;
};

我们把上一个章节的示例代码改造一下,打印一下 React.createElement输出的内容, 如下所示:

import React from 'react'
import ReactDOM from 'react-dom'

const element = <h3>Hello, Eagle!</h3>
console.log(element)

ReactDOM.render(
  element,
  document.getElementById('root')
)

控制台打印内容如下:

Snipaste_2021-07-18_17-17-00.png

控制台打印出来的对象也印证了我们在源码中所看到的那样,最终都会变成 ReactElement 类型的对象,然后再传给 ReactDOM.render 去进行渲染。