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))
),
}
}关键设计点
- children 拍平 ——
children.flat()处理嵌套数组(如{list.map(...)}) - 过滤假值 ——
null、undefined、false、true不应该渲染 - 文本节点统一化 —— 字符串和数字都包装成
{ type: 'TEXT_ELEMENT', ... }的 VNode 结构