JSX 是 JavaScript 的一种语法扩展,它允许你在 JavaScript 文件中编写类似 HTML 的标记。虽然还有其他编写组件的方式,但大多数 React 开发者更喜欢 JSX 的简洁性,并且大多数代码库都使用它。
你将学习到
- 为什么 React 将标记与渲染逻辑混合在一起
- JSX 与 HTML 有何不同
- 如何用 JSX 显示信息
JSX:将标记放入 JavaScript
🌐 JSX: Putting markup into JavaScript
网络是建立在 HTML、CSS 和 JavaScript 之上的。多年来,网页开发者将内容保存在 HTML 中,设计保存在 CSS 中,而逻辑保存在 JavaScript 中——通常在不同的文件中!内容在 HTML 中标记,而页面的逻辑则单独存在于 JavaScript 中:
🌐 The Web has been built on HTML, CSS, and JavaScript. For many years, web developers kept content in HTML, design in CSS, and logic in JavaScript—often in separate files! Content was marked up inside HTML while the page’s logic lived separately in JavaScript:


HTML


JavaScript
但是,随着网络变得越来越互动,逻辑越来越多地决定内容。JavaScript 控制了 HTML!这就是为什么在 React 中,渲染逻辑和标记会一起存在于同一个地方——组件中。
🌐 But as the Web became more interactive, logic increasingly determined content. JavaScript was in charge of the HTML! This is why in React, rendering logic and markup live together in the same place—components.


Sidebar.js React 组件


Form.js React 组件
将按钮的渲染逻辑和标记放在一起可以确保它们在每次编辑时保持同步。相反,不相关的细节,例如按钮的标记和侧边栏的标记,则彼此隔离,这样单独更改其中任何一个都会更安全。
🌐 Keeping a button’s rendering logic and markup together ensures that they stay in sync with each other on every edit. Conversely, details that are unrelated, such as the button’s markup and a sidebar’s markup, are isolated from each other, making it safer to change either of them on their own.
每个 React 组件都是一个 JavaScript 函数,它可能包含一些 React 渲染到浏览器的标记。React 组件使用一种叫做 JSX 的语法扩展来表示这些标记。JSX 看起来很像 HTML,但它更严格一些,并且可以显示动态信息。理解这一点的最好方法是将一些 HTML 标记转换为 JSX 标记。
🌐 Each React component is a JavaScript function that may contain some markup that React renders into the browser. React components use a syntax extension called JSX to represent that markup. JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information. The best way to understand this is to convert some HTML markup to JSX markup.
将 HTML 转换为 JSX
🌐 Converting HTML to JSX
假设你有一些(完全有效的)HTML:
🌐 Suppose that you have some (perfectly valid) HTML:
<h1>Hedy Lamarr's Todos</h1>
<img
src="https://i.imgur.com/yXOvdOSs.jpg"
alt="Hedy Lamarr"
class="photo"
>
<ul>
<li>Invent new traffic lights
<li>Rehearse a movie scene
<li>Improve the spectrum technology
</ul>你想把它放到你的组件中:
🌐 And you want to put it into your component:
export default function TodoList() {
return (
// ???
)
}如果你按原样复制并粘贴它,它将不起作用:
🌐 If you copy and paste it as is, it will not work:
export default function TodoList() { return ( // This doesn't quite work! <h1>Hedy Lamarr's Todos</h1> <img src="https://i.imgur.com/yXOvdOSs.jpg" alt="Hedy Lamarr" class="photo" > <ul> <li>Invent new traffic lights <li>Rehearse a movie scene <li>Improve the spectrum technology </ul>
这是因为 JSX 比 HTML 更严格,并且有更多规则!如果你阅读上面的错误信息,它们会指导你修复标记,或者你可以遵循下面的指南。
🌐 This is because JSX is stricter and has a few more rules than HTML! If you read the error messages above, they’ll guide you to fix the markup, or you can follow the guide below.
JSX 规则
🌐 The Rules of JSX
1. 返回一个根元素
🌐 1. Return a single root element
要从组件中返回多个元素,用一个父标签将它们封装起来。
🌐 To return multiple elements from a component, wrap them with a single parent tag.
例如,你可以使用一个 <div>:
🌐 For example, you can use a <div>:
<div>
<h1>Hedy Lamarr's Todos</h1>
<img
src="https://i.imgur.com/yXOvdOSs.jpg"
alt="Hedy Lamarr"
class="photo"
>
<ul>
...
</ul>
</div>如果你不想在标记中添加额外的 <div>,你可以改用 <> 和 </>:
🌐 If you don’t want to add an extra <div> to your markup, you can write <> and </> instead:
<>
<h1>Hedy Lamarr's Todos</h1>
<img
src="https://i.imgur.com/yXOvdOSs.jpg"
alt="Hedy Lamarr"
class="photo"
>
<ul>
...
</ul>
</>这个空标签称为 Fragment. Fragment 允许你对元素进行分组,而不会在浏览器的 HTML 树中留下任何痕迹。
🌐 This empty tag is called a Fragment. Fragments let you group things without leaving any trace in the browser HTML tree.
深入研究
🌐 Why do multiple JSX tags need to be wrapped?
JSX 看起来像 HTML,但在底层它会被转换成普通的 JavaScript 对象。你不能从一个函数中返回两个对象,除非将它们封装在一个数组中。这也解释了为什么你不能返回两个 JSX 标签,除非将它们封装在另一个标签或 Fragment 中。
🌐 JSX looks like HTML, but under the hood it is transformed into plain JavaScript objects. You can’t return two objects from a function without wrapping them into an array. This explains why you also can’t return two JSX tags without wrapping them into another tag or a Fragment.
2. 关闭所有标签
🌐 2. Close all the tags
JSX要求标签必须显式关闭:自闭合标签如<img>必须变为<img />,而封装标签如<li>oranges必须写成<li>oranges</li>。
🌐 JSX requires tags to be explicitly closed: self-closing tags like <img> must become <img />, and wrapping tags like <li>oranges must be written as <li>oranges</li>.
Hedy Lamarr 的图片和列表项看起来是这样闭合的:
🌐 This is how Hedy Lamarr’s image and list items look closed:
<>
<img
src="https://i.imgur.com/yXOvdOSs.jpg"
alt="Hedy Lamarr"
class="photo"
/>
<ul>
<li>Invent new traffic lights</li>
<li>Rehearse a movie scene</li>
<li>Improve the spectrum technology</li>
</ul>
</>3. camelCase 所有 大多数的事情!
🌐 3. camelCase all most of the things!
JSX 会转化为 JavaScript,而在 JSX 中编写的属性会变成 JavaScript 对象的键。在你自己的组件中,你经常会希望将这些属性读取到变量中。但 JavaScript 对变量名有一定限制。例如,它们的名称不能包含连字符或是像 class 这样的保留字。
🌐 JSX turns into JavaScript and attributes written in JSX become keys of JavaScript objects. In your own components, you will often want to read those attributes into variables. But JavaScript has limitations on variable names. For example, their names can’t contain dashes or be reserved words like class.
这就是为什么在 React 中,许多 HTML 和 SVG 属性使用驼峰命名法。例如,不是使用 stroke-width,而是使用 strokeWidth。由于 class 是保留字,在 React 中你需要使用 className,名称取自对应的 DOM 属性 :
🌐 This is why, in React, many HTML and SVG attributes are written in camelCase. For example, instead of stroke-width you use strokeWidth. Since class is a reserved word, in React you write className instead, named after the corresponding DOM property:
<img
src="https://i.imgur.com/yXOvdOSs.jpg"
alt="Hedy Lamarr"
className="photo"
/>你可以在 DOM 组件属性列表 中找到所有这些属性。如果你弄错了,不用担心——React 会在 浏览器控制台 打印一条可能的更正信息。
🌐 You can find all these attributes in the list of DOM component props. If you get one wrong, don’t worry—React will print a message with a possible correction to the browser console.
专业提示:使用 JSX 转换器
🌐 Pro-tip: Use a JSX Converter
将现有标记中的所有这些属性转换可能很繁琐!我们建议使用一个转换器将现有的 HTML 和 SVG 转换为 JSX。转换器在实际中非常有用,但理解其背后的原理仍然值得,这样你就可以自如地自己编写 JSX。
🌐 Converting all these attributes in existing markup can be tedious! We recommend using a converter to translate your existing HTML and SVG to JSX. Converters are very useful in practice, but it’s still worth understanding what is going on so that you can comfortably write JSX on your own.
这是你的最终结果:
🌐 Here is your final result:
export default function TodoList() { return ( <> <h1>Hedy Lamarr's Todos</h1> <img src="https://i.imgur.com/yXOvdOSs.jpg" alt="Hedy Lamarr" className="photo" /> <ul> <li>Invent new traffic lights</li> <li>Rehearse a movie scene</li> <li>Improve the spectrum technology</li> </ul> </> ); }
回顾
现在你知道为什么 JSX 存在以及如何在组件中使用它了:
🌐 Now you know why JSX exists and how to use it in components:
- React 组件将渲染逻辑与标记组合在一起,因为它们是相关的。
- JSX 类似于 HTML,但有一些不同。如果需要,你可以使用一个转换器。
- 错误消息通常会为你指明修复标记的正确方向。
挑战 1 of 1: 将一些 HTML 转换为 JSX
🌐 Convert some HTML to JSX
此 HTML 被粘贴到一个组件中,但它不是有效的 JSX。请修复它:
🌐 This HTML was pasted into a component, but it’s not valid JSX. Fix it:
export default function Bio() { return ( <div class="intro"> <h1>Welcome to my website!</h1> </div> <p class="summary"> You can find my thoughts here. <br><br> <b>And <i>pictures</b></i> of scientists! </p> ); }
是手动还是使用转换器由你决定!
🌐 Whether to do it by hand or using the converter is up to you!