ReactElement

react

  • Flow - JavaScript静态类型检查工具
  • Rollup - 另一个前端模块化的打包工具
  • monorepo VS multirepo(集中管理 vs 多元化)管理组织代码的方式,顾名思义 monorepo 就是把所有的相关项目都放在一个仓库中(比如 React, Angular, Babel, Google…),multirepo 则是按模块分为多个仓库。
  • React 的核心入口文件是packages/react/index.js

使用JSX来编写的组件会被编译成调用React.createElement的形式

class App extends Component {
  render() {
    return (
        <p src={logo} className="App-logo">Edit <code>src/App.js</code> and save to reload.</p>
        )
    }
}

经过Babel编译后:

React.createElement(
      "p",
      { src: logo, className: "App-logo"},
      "Edit ",
      React.createElement(
        "code",
        null,
        "src/App.js"
      ),
      " and save to reload."
    )

看createElement源码:

function createElement(type, config, children) {
    ...
    // 返回出ReactElement
    return ReactElement(
      type,
      key,
      ref,
      self,
      source,
      ReactCurrentOwner.current,
      props,
    );
}

之后ReactElement

const ReactElement = function(type, key, ref, self, source, owner, props) {
  const element = {
    // Symbol类型的tag唯一标示这个对象是一个React Element类型
    // This tag allows us to uniquely identify this as a React Element
    $$typeof: REACT_ELEMENT_TYPE, // REACT_ELEMENT_TYPE:Symbol.for('react.element')

    // Built-in properties that belong on the element
    type: type, // 如果当前ReactElement是一个ReactComponent,那这里将是它对应的Constructor;而普通HTML标签,一般都是String
    key: key,
    ref: ref,
    props: props,

    // Record the component responsible for creating this element.
    _owner: owner,
  };

  return element;
};

ReactElement主要分为DOM Elements和Component Elements两种,我们称这样的对象为ReactElement。

  • DOM Elements 当节点的type属性为字符串时,它代表是普通的节点,如div,span:
    {
    type: 'button',
    props: {
      className: 'button button-blue',
      children: {
        type: 'b',
        props: {
          children: 'OK!'
        }
      }
    }
    }
    
  • Component Elements 当节点的type属性为一个函数或一个类时,它代表自定义的节点:
    class Button extends React.Component {
    render() {
      const { children, color } = this.props;
      return {
        type: 'button',
        props: {
          className: 'button button-' + color,
          children: {
            type: 'b',
            props: {
              children: children
            }
          }
        }
      };
    }
    }
    // Component Elements
    {
    type: Button,
    props: {
      color: 'blue',
      children: 'OK!'
    }
    }
    
react16.8.6
JSRUN前端笔记, 是针对前端工程师开放的一个笔记分享平台,是前端工程师记录重点、分享经验的一个笔记本。JSRUN前端采用的 MarkDown 语法 (极客专用语法), 这里属于IT工程师。