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.

你将学习到

  • 如何传递带引号的字符串

    ¥How to pass strings with quotes

  • 如何使用大括号在 JSX 中引用 JavaScript 变量

    ¥How to reference a JavaScript variable inside JSX with curly braces

  • 如何使用大括号在 JSX 中调用 JavaScript 函数

    ¥How to call a JavaScript function inside JSX with curly braces

  • 如何使用大括号在 JSX 中使用 JavaScript 对象

    ¥How to use a JavaScript object inside JSX with curly braces

传递带引号的字符串

¥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}> 无效。

    ¥As text directly inside a JSX tag: <h1>{name}'s To Do List</h1> works, but <{tag}>Gregorio Y. Zara's To Do List</{tag}> will not.

  2. 作为紧跟在 = 符号后面的属性:src={avatar} 将读取 avatar 变量,但 src="{avatar}" 将传递字符串 "{avatar}"

    ¥As attributes immediately following the = sign: src={avatar} will read the avatar variable, but src="{avatar}" will pass the string "{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 属性作为字符串传递。

    ¥JSX attributes inside quotes are passed as strings.

  • 大括号让你可以将 JavaScript 逻辑和变量带入你的标记中。

    ¥Curly braces let you bring JavaScript logic and variables into your markup.

  • 它们在 JSX 标签内容内部或紧接在属性中的 = 之后工作。

    ¥They work inside the JSX tag content or immediately after = in attributes.

  • {{}} 不是特殊语法:它是一个藏在 JSX 大括号内的 JavaScript 对象。

    ¥{{ and }} is not special syntax: it’s a JavaScript object tucked inside JSX curly braces.

挑战 1 / 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?

¥

Look for what’s inside the curly braces. Are we putting the right thing there?


React 中文网 - 粤ICP备13048890号