什么是 JSX
What is JSX
一句话:JavaScript 的语法扩展, 让你在 JS 里写类似 HTML 的结构。浏览器不认识它, 要经过 Babel 编译成普通函数调用。
编译成什么(这是考点): 旧版编译成React.createElement(type, props, ...children);React 17 之后用新的 JSX 转换, 编译成 _jsx(...), 所以不用再手动import React 了。
要说清的几条规则:
- 必须有单一根节点—— 因为函数只能返回一个值。 不想多套
div就用Fragment(见 #338)。 - 属性名用小驼峰——
className(因为class是 JS 关键字)、htmlFor、onClick。 {}里放表达式, 不能放语句 —— 所以条件渲染用三元或&&,不能写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 aFragment(see #338). - Attribute names are camelCase —
className(becauseclassis a JS keyword),htmlFor,onClick. {}holds an expression, not a statement — so conditional rendering uses a ternary or&&, neverif.- 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.