JSX 中使用大括号的 JavaScript

JSX 让你可以在 JavaScript 文件中编写类似 HTML 的标记,将渲染逻辑和内容放在同一个地方。有时你可能想在这些标记中添加一点 JavaScript 逻辑或引用动态属性。在这种情况下,你可以在 JSX 中使用大括号来打开通向 JavaScript 的窗口。

🌐 JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content in the same place. Sometimes you will want to add a little JavaScript logic or reference a dynamic property inside that markup. In this situation, you can use curly braces in your JSX to open a window to JavaScript.

你将学习到

  • 如何传递带引号的字符串
  • 如何使用大括号在 JSX 中引用 JavaScript 变量
  • 如何使用大括号在 JSX 中调用 JavaScript 函数
  • 如何使用大括号在 JSX 中使用 JavaScript 对象

传递带引号的字符串

🌐 Passing strings with quotes

当你想将一个字符串属性传递给 JSX 时,你可以将它放在单引号或双引号中:

🌐 When you want to pass a string attribute to JSX, you put it in single or double quotes:

export default function Avatar() {
  return (
    <img
      className="avatar"
      src="https://i.imgur.com/7vQD0fPs.jpg"
      alt="Gregorio Y. Zara"
    />
  );
}

这里,"https://i.imgur.com/7vQD0fPs.jpg""Gregorio Y. Zara" 作为字符串传递。

🌐 Here, "https://i.imgur.com/7vQD0fPs.jpg" and "Gregorio Y. Zara" are being passed as strings.

但是如果你想动态指定 srcalt 文本呢?你可以 使用 JavaScript 的值,通过将 "" 替换为 {}

🌐 But what if you want to dynamically specify the src or alt text? You could use a value from JavaScript by replacing " and " with { and }:

export default function Avatar() {
  const avatar = 'https://i.imgur.com/7vQD0fPs.jpg';
  const description = 'Gregorio Y. Zara';
  return (
    <img
      className="avatar"
      src={avatar}
      alt={description}
    />
  );
}

注意 className="avatar"src={avatar} 之间的区别,className="avatar" 指定了一个 "avatar" CSS 类名,使图片呈圆形,而 src={avatar} 则读取名为 avatar 的 JavaScript 变量的值。这是因为大括号允许你在标记中直接使用 JavaScript!

🌐 Notice the difference between className="avatar", which specifies an "avatar" CSS class name that makes the image round, and src={avatar} that reads the value of the JavaScript variable called avatar. That’s because curly braces let you work with JavaScript right there in your markup!

使用大括号:通向 JavaScript 世界的一扇窗

🌐 Using curly braces: A window into the JavaScript world

JSX 是一种编写 JavaScript 的特殊方式。这意味着可以在其中使用 JavaScript——使用大括号 { }。下面的例子首先为科学家声明了一个名字 name,然后将其用大括号嵌入到 <h1> 中:

🌐 JSX is a special way of writing JavaScript. That means it’s possible to use JavaScript inside it—with curly braces { }. The example below first declares a name for the scientist, name, then embeds it with curly braces inside the <h1>:

export default function TodoList() {
  const name = 'Gregorio Y. Zara';
  return (
    <h1>{name}'s To Do List</h1>
  );
}

尝试将 name 的值从 'Gregorio Y. Zara' 改为 'Hedy Lamarr'。看看列表标题如何变化?

🌐 Try changing the name’s value from 'Gregorio Y. Zara' to 'Hedy Lamarr'. See how the list title changes?

在大括号之间,任何 JavaScript 表达式都可以使用,包括像 formatDate() 这样的函数调用:

🌐 Any JavaScript expression will work between curly braces, including function calls like formatDate():

const today = new Date();

function formatDate(date) {
  return new Intl.DateTimeFormat(
    'en-US',
    { weekday: 'long' }
  ).format(date);
}

export default function TodoList() {
  return (
    <h1>To Do List for {formatDate(today)}</h1>
  );
}

何处使用大括号

🌐 Where to use curly braces

你只能在 JSX 中以两种方式使用大括号:

🌐 You can only use curly braces in two ways inside JSX:

  1. 作为文本 直接放在 JSX 标签内:<h1>{name}'s To Do List</h1> 可行,但 <{tag}>Gregorio Y. Zara's To Do List</{tag}> 不行。
  2. 作为属性 紧跟在 = 符号后:src={avatar} 将读取 avatar 变量,但 src="{avatar}" 将传递字符串 "{avatar}"

使用“双大括号”:JSX 中的 CSS 和其他对象

🌐 Using “double curlies”: CSS and other objects in JSX

除了字符串、数字和其他 JavaScript 表达式之外,你甚至可以在 JSX 中传递对象。对象也用大括号表示,比如 { name: "Hedy Lamarr", inventions: 5 }。因此,要在 JSX 中传递一个 JS 对象,你必须将对象封装在另一对大括号中:person={{ name: "Hedy Lamarr", inventions: 5 }}

🌐 In addition to strings, numbers, and other JavaScript expressions, you can even pass objects in JSX. Objects are also denoted with curly braces, like { name: "Hedy Lamarr", inventions: 5 }. Therefore, to pass a JS object in JSX, you must wrap the object in another pair of curly braces: person={{ name: "Hedy Lamarr", inventions: 5 }}.

在 JSX 中,你可能会看到这种内联 CSS 样式。React 并不要求你使用内联样式(在大多数情况下,CSS 类效果很好)。但是当你需要内联样式时,你需要将一个对象传递给 style 属性:

🌐 You may see this with inline CSS styles in JSX. React does not require you to use inline styles (CSS classes work great for most cases). But when you need an inline style, you pass an object to the style attribute:

export default function TodoList() {
  return (
    <ul style={{
      backgroundColor: 'black',
      color: 'pink'
    }}>
      <li>Improve the videophone</li>
      <li>Prepare aeronautics lectures</li>
      <li>Work on the alcohol-fuelled engine</li>
    </ul>
  );
}

尝试更改 backgroundColorcolor 的值。

🌐 Try changing the values of backgroundColor and color.

当你这样写时,你真的可以看到大括号内的 JavaScript 对象:

🌐 You can really see the JavaScript object inside the curly braces when you write it like this:

<ul style={
{
backgroundColor: 'black',
color: 'pink'
}
}>

下次你在 JSX 中看到 {{}} 时,要知道它们不过是 JSX 大括号里的一个对象而已!

🌐 The next time you see {{ and }} in JSX, know that it’s nothing more than an object inside the JSX curlies!

易犯错误

内联 style 属性使用驼峰命名法编写。例如,HTML <ul style="background-color: black"> 在你的组件中将写作 <ul style={{ backgroundColor: 'black' }}>

🌐 Inline style properties are written in camelCase. For example, HTML <ul style="background-color: black"> would be written as <ul style={{ backgroundColor: 'black' }}> in your component.

使用 JavaScript 对象和大括号更有趣

🌐 More fun with JavaScript objects and curly braces

你可以将多个表达式移动到一个对象中,并在你的 JSX 大括号内引用它们:

🌐 You can move several expressions into one object, and reference them in your JSX inside curly braces:

const person = {
  name: 'Gregorio Y. Zara',
  theme: {
    backgroundColor: 'black',
    color: 'pink'
  }
};

export default function TodoList() {
  return (
    <div style={person.theme}>
      <h1>{person.name}'s Todos</h1>
      <img
        className="avatar"
        src="https://i.imgur.com/7vQD0fPs.jpg"
        alt="Gregorio Y. Zara"
      />
      <ul>
        <li>Improve the videophone</li>
        <li>Prepare aeronautics lectures</li>
        <li>Work on the alcohol-fuelled engine</li>
      </ul>
    </div>
  );
}

在这个例子中,person JavaScript 对象包含一个 name 字符串和一个 theme 对象:

🌐 In this example, the person JavaScript object contains a name string and a theme object:

const person = {
name: 'Gregorio Y. Zara',
theme: {
backgroundColor: 'black',
color: 'pink'
}
};

组件可以像这样使用来自 person 的这些值:

🌐 The component can use these values from person like so:

<div style={person.theme}>
<h1>{person.name}'s Todos</h1>

JSX 作为一种模板语言非常精简,因为它允许你使用 JavaScript 组织数据和逻辑。

🌐 JSX is very minimal as a templating language because it lets you organize data and logic using JavaScript.

回顾

现在你几乎了解了 JSX 的一切:

🌐 Now you know almost everything about JSX:

  • 引号内的 JSX 属性作为字符串传递。
  • 大括号让你可以将 JavaScript 逻辑和变量带入你的标记中。
  • 它们在 JSX 标签内容内部或紧跟在属性中的 = 之后工作。
  • {{}} 不是特殊语法:它们是放在 JSX 大括号里的 JavaScript 对象。

挑战 1 of 3:
修复错误

🌐 Fix the mistake

这段代码会崩溃,并显示错误 Objects are not valid as a React child

🌐 This code crashes with an error saying Objects are not valid as a React child:

const person = {
  name: 'Gregorio Y. Zara',
  theme: {
    backgroundColor: 'black',
    color: 'pink'
  }
};

export default function TodoList() {
  return (
    <div style={person.theme}>
      <h1>{person}'s Todos</h1>
      <img
        className="avatar"
        src="https://i.imgur.com/7vQD0fPs.jpg"
        alt="Gregorio Y. Zara"
      />
      <ul>
        <li>Improve the videophone</li>
        <li>Prepare aeronautics lectures</li>
        <li>Work on the alcohol-fuelled engine</li>
      </ul>
    </div>
  );
}

你能找到问题所在吗?

🌐 Can you find the problem?