Skip to content

JSX 与 createElement

什么是 JSX?

JSX 是 JavaScript 的语法扩展,允许我们在 JS 中编写类似 HTML 的代码。但浏览器无法直接理解 JSX,它需要被编译成普通的 JavaScript 函数调用。

jsx
// 你写的 JSX
const element = <div className="hello">Hello World</div>

// Babel/SWC 编译后
const element = createElement('div', { className: 'hello' }, 'Hello World')

实现 createElement

createElement 是整个 React 的起点。它的作用是将 JSX 转换后的函数调用生成一个虚拟 DOM 对象(VNode)

typescript
export interface VNode {
  type: string | Function | symbol
  props: Record<string, any>
  children: (VNode | string)[]
}

export function createElement(
  type: string | Function | symbol,
  props: Record<string, any> | null,
  ...children: any[]
): VNode {
  return {
    type,
    props: props || {},
    children: children
      .flat()
      .filter((child) => child != null && child !== false && child !== true)
      .map((child) =>
        typeof child === 'object' ? child : createTextElement(String(child))
      ),
  }
}

关键设计点

  1. children 拍平 —— children.flat() 处理嵌套数组(如 {list.map(...)}
  2. 过滤假值 —— nullundefinedfalsetrue 不应该渲染
  3. 文本节点统一化 —— 字符串和数字都包装成 { type: 'TEXT_ELEMENT', ... } 的 VNode 结构

用心学习,用代码说话 💻