DrillLab
第 55 / 105 道55 / 105 · #326

什么是 JSX

What is JSX

先自己答,再往下看Answer it yourself first

一句话:JavaScript 的语法扩展, 让你在 JS 里写类似 HTML 的结构。浏览器不认识它, 要经过 Babel 编译成普通函数调用。

编译成什么(这是考点): 旧版编译成React.createElement(type, props, ...children)React 17 之后用新的 JSX 转换, 编译成 _jsx(...), 所以不用再手动import React 了。

要说清的几条规则:

  • 必须有单一根节点—— 因为函数只能返回一个值。 不想多套 div 就用Fragment(见 #338)。
  • 属性名用小驼峰——className(因为class 是 JS 关键字)、htmlForonClick
  • {} 里放表达式, 不能放语句 —— 所以条件渲染用三元或&&,不能写 if
  • JSX 默认转义, 所以天然防 XSS; 要插 HTML 得显式写dangerouslySetInnerHTML——名字故意起得难听, 就是让你警觉。

会追问:「JSX 是必须的吗?」—— 不是,你可以手写createElement, 只是没人愿意。JSX 的价值是让 「UI 结构」在代码里长得像结构

In one line: a syntax extension for JavaScript that lets you write HTML-like structure inside JS. The browser does not understand it — Babel compiles it into plain function calls.

What it compiles to (this is the part being tested): old versions produced React.createElement(type, props, ...children); since React 17 the new JSX transform emits _jsx(...), which is why you no longer have to write import React by hand.

The rules you should state clearly:

  • One root node is required — a function can only return one value. If you do not want another div, use a Fragment (see #338).
  • Attribute names are camelCase className (because class is a JS keyword), htmlFor, onClick.
  • {} holds an expression, not a statement — so conditional rendering uses a ternary or &&, never if.
  • JSX escapes by default, so you get XSS protection for free; injecting raw HTML takes an explicit dangerouslySetInnerHTML the name is deliberately ugly so that you stop and think.

Follow-up: “Is JSX mandatory?” — no, you can call createElement yourself, nobody wants to. The value of JSX is that UI structure looks like structure in the code.

JSXJSX 编译成什么示意Illustrative
1// 你写的
2const el = <button className="btn" onClick={handle}>点我</button>;
3
4// Babel 编译后(React 17 之前)
5const el = React.createElement(
6 "button",
7 { className: "btn", onClick: handle },
8 "点我",
9);
10
11// {} 里只能放表达式
12{if (ok) <A />} // ✗ 语法错误
13{ok ? <A /> : null} // ✓
14{ok && <A />} // ✓(注意 0 会被渲染出来,见 #281)
1// What you write
2const el = <button className="btn" onClick={handle}>Click me</button>;
3
4// After Babel compiles it (before React 17)
5const el = React.createElement(
6 "button",
7 { className: "btn", onClick: handle },
8 "Click me",
9);
10
11// Only an expression can go inside {}
12{if (ok) <A />} // ✗ syntax error
13{ok ? <A /> : null} // ✓
14{ok && <A />} // ✓ (careful: 0 does get rendered, see #281)