diff --git a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/index.md b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/index.md index 9a9006e6134438..a6017dc5174113 100644 --- a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/index.md +++ b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/index.md @@ -9,128 +9,110 @@ tags: - 客户端 translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks --- -
{{LearnSidebar}}
- -

JavaScript 框架是现代前端 web 开发的重要部分,为开发人员提供了构建可伸缩、交互式 web 应用程序的经过测试的工具。许多现代公司使用框架作为工具的标准部分,因此许多前端开发工作现在需要框架经验。

- -

作为一个有抱负的前端开发人员,很难找出从哪里开始学习框架——有这么多不同的框架可供选择,新的问题出现,他们大多以类似的方式工作,但做一些不同的事情,还有一些具体的事情时要小心使用框架。

- -

在这一系列文章中,我们旨在为您提供一个舒适的起点,帮助您开始学习框架。我们的目标不是详尽地教给你所有你需要知道的关于 React/ReactDOM,或者 Vue,或者其他一些特定的框架;框架团队自己的文档已经完成了这项工作。相反,我们想备份和首先回答更基本的问题,如:

- - - -

在此之后,我们将提供一些教程,介绍一些主要框架的基本内容,为您提供足够的上下文和熟悉感,以便您自己开始更深入地学习。我们希望你以一种实用的方式来学习框架,不要忘记 web 平台的基本最佳实践,比如可访问性。

- -

通过“客户端框架介绍”即刻开始

- -

前提条件

- -

在尝试学习客户端框架 (HTML、CSS,特别是 JavaScript) 之前,您应该首先真正学习核心 web 语言的基础知识。

- -

如果你理解了框架底层的基础 Web 平台特性,你将能编写更加健壮和专业的代码,更容易地排除问题。

- -

说明指导

- -
-
1. 客户端框架介绍
-
我们首先从以下话题开始研究框架,框架领域的总览,JavaScript 和框架历史的简介,为什么需要框架以及框架能带给我们什么,如何考虑选择一个框架开始学习,有什么其它的客户端框架可供选择。
-
2. 框架的主要特性
-
每种 JavaScript 框架都有自己不同的方式更新 DOM,处理浏览器事件,为开发者提供愉悦的使用体验,这篇文章将探索“四大”框架的主要特性,从高级角度探讨框架的工作方式以及它们之间的区别。
-
- -

React 教程

- -
-

备注: React 教程最后测试于 2020 年 5 月,基于 React/ReactDOM 16.13.1 和 create-react-app 3.4.1.

- -

如果你需要确认你的代码与我们的版本区别,你可以在我们的todo-react repository仓库找到 React 应用示例代码的完整版本。想要获取当前最新的版本,查看https://mdn.github.io/todo-react-build/.

-
- -
-
1. 开始使用 React
-
此章节我们将向 React 打招呼。我们将能发现有关 React 的背景和使用场景的一些细节,在我们的计算机上设置基本的 React 工具链,创建和运行简单的入门应用,学习 React 在这个过程是如何工作的。
-
2. 开始我们的 React 待办清单
-
假设我们计划使用 React 创建 proof-of-concept,一个允许用户添加,编辑和删除工作任务,不删除的情况标记任务完成的应用。此章节将带你完成基本的App组件结构和样式,为最后即将添加的独立组件定义和交互做好准备。
-
3. 组件化我们的 React 应用
-
到这个阶段,我们的应用仍是一个单一结构。在让它工作之前,我们需要将它分解为可管理的描述性组件。React 对于组件没有任何硬性规定--这完全取决于你!在此章节我们将向你展示一个合理的方式来将我们的应用分解成 组件。
-
4. React 交互:事件和状态
-
我们的组件化计划已经完成,现在是时候开始将我们的应用从一个完全静态的界面更新成允许交互和变更的界面。在这个章节我们将继续研究事件和状态,借此实现上述功能。
-
5. React 交互:编辑,过滤,条件渲染
-
我们已经接近 React 旅程的终点(至少目前是这样),我们将对我们的 Todo 列表应用的主要功能区域做最后的更改。这包括允许编辑现有的任务,在所有列表,已完成列表和未完成列表中过滤任务。在这个过程中我们将研究条件渲染。
-
6. React 的可访问性支持
-
在我们最后的教程章节,我们将重点介绍可访问性,包括 React 的焦点管理,这可以提高可用性,降低纯键盘用户和屏幕阅读器用户的困扰。
-
7. React 资源
-
我们的最后章节提供了一个 React 资源列表,供你用于进一步的学习。
-
- -

Ember 教程

- -
-

备注: Ember 教程最后测试于 2020 年 5 月,基于 Ember/Ember CLI version 3.18.0.

- -

如果你需要确认你的代码与我们的版本区别,你可以在ember-todomvc-tutorial repository找到 Ember 应用示例代码的完整版本。想要获取当前最新的版本,查看https://nullvoxpopuli.github.io/ember-todomvc-tutorial/ (这还包含了本教程未覆盖到的一些额外的特性)。

-
- -
-
1. 开始使用 Ember
-
在我们的 Ember 第一章节中我们将了解 Ember 的工作原理及其用途,本地安装 Ember 工具链,创建一个示例应用,然后做一些初始化设置以便开始开发。
-
2. Ember 应用结构和组件化
-
在此章节,我们将继续规划我们的 TodoMVC Ember 应用,为其添加 HTML 部分,随后将这些 HTML 分解为组件。
-
3. Ember 交互:事件,类和状态
-
至此,我们将添加一些交互行为到我们的应用,使其能够添加和显示新的待办事项。在此过程中,我们将研究如何在 Ember 中使用事件,创建包含 JavaScript 代码的组件类来控制交互功能,并且设置服务来跟踪我们的应用的数据状态。
-
4. Ember 交互:页脚功能,条件渲染
-
现在是时候开始在我们的应用中处理页脚功能了。这里我们将更新待办事项计数器以正确显示待完成待办事项的数量,并正确地为已完成事项应用样式(i.e. 对应列表项的复选框处于选中状态)。我们还将实装我们的“Clear completed”按钮。在这个过程中,我们将学习在我们的模板中使用条件渲染。
-
5. Ember 路由
-
在此章节我们学习路由,有时也称为 URL-based 过滤。我们将使用它来为三个待办视图------"All","Active"和"Completed"提供全局唯一的 URL。
-
6. Ember 资源和疑难解答
-
我们的最后一个 Ember 章节提供了一个供你进一步学习的资源列表,还有一些有用的疑难解答和其他信息。
-
- -

Vue 教程

- -
-

备注: Vue 教程最后测试于 2020 年 5 月,基于 Vue 2.6.11.

- -

如果你需要确认你的代码与我们的版本区别,你可以在todo-vue repository找到 Vue 应用示例代码的完整版本。想要获取当前当前最新的版本,查看https://mdn.github.io/todo-vue/dist/.

-
- -
-
1. 开始使用 Vue
-
现在让我们开始介绍 Vue,我们的第三个框架。在此章节我们将简单了解 Vue 的背景,学习如何安装 Vue 以及如何创建一个新项目,学习整个项目的高级架构以及独立的组件,了解如何在本地运行这个项目,并准备开始构建我们的示例。
-
2. 创建我们的第一个 Vue 组件
-
现在是时候深入 Vue,创建我们自己的自定义组件了--我们将从创建一个用来展示待办列表项目的组件开始。在这个过程中,我们将学习一些重要的概念例如在一个组件中调用另一个组件,通过 props 传递数据给另一个组件并保存数据状态。
-
3. 渲染 Vue 组件列表
-
至此我们已经得到了一个完全可用的组件,我们现在已经准备好添加多个ToDoItem 组件到我们的应用中了。在此章节我们将了解如何添加一组待办项数据到我们的App.vue组件,这组数据我们随后使用v-for指令将它们循环并显示到ToDoItem组件中。
-
4. 添加一个新的待办表单:Vue 事件,方法和模型
-
现在我们的应用已经有了示例数据和一个循环来将每条数据渲染到ToDoItem中。下一步我们要做的是让用户能够输入他们自己的待办事项到这个应用中。 为此我们需要一个文本输入框<input>,一个在数据提交时触发的事件,一个在数据提交时被触发来添加数据和渲染列表的方法和一个用来控制数据的模型。这就是这个章节我们将要介绍的内容。
-
5. 使用 CSS 美化 Vue 组件
-
终于到了美化我们的应用的时间了。在此章节我们将探索用 CSS 美化 Vue 组件的不同方法。
-
6. 使用 Vue 计算属性
-
在这个章节我们将添加一个显示已完成待办项目数量的计数器,使用 Vue 的一个叫做计算属性的特性。计算属性与方法相似,但是只有它的依赖内容变更时才会再次运作。
-
7. Vue 条件渲染:编辑既有待办项
-
现在是时候加入我们还未实现一个主要功能部分了------编辑既有待办项。为了实现这个功能,我们将利用 Vue 的条件渲染能力------v-ifv-else来使既有待办项目在查看状态和文本编辑状态之间切换。我们还将添加删除待办项的功能。
-
8. 使用 Vue refs 进行焦点管理
-
我们快要完成 Vue 的使用了。最后要看的一个功能是焦点管理,换种说法,如何改善我们的应用的键盘可操作性。我们将解决这个问题,通过 Vue refs------一个允许你直接操作虚拟 DOM 的底层 DOM,或在组件中直接操作其子组件内部 DOM 结构的高级特性。
-
9. Vue 资源
-
我们将提供一个你可以用来进一步学习的资源列表来圆满结束我们的 Vue 学习教程,从这个列表中你也可以获取一些有用的技巧。
-
- -

我们应该选择哪个框架?

- -

我们在这里发布专注于主要三大框架的系列说明文章------React/ReactDOM,Ember和Vue的一些原因如下:

- - - -

我们想在前面说一下------我们没有因为我们认为它们是最好的或者我们赞同它们而选择这些我们正在关注的框架。我们只是认为它们在上面这些方面评价比较高。

- -

值得一提的是我们也希望在我们的初版发布时能够包含更多框架的内容,但是我们最终决定先把初版内容发布出来随后在此基础上再慢慢添加更多框架内容,而不是延后更长的时间。如果你最喜欢的框架没有包含在这部分内容中而且你想帮助改善这个情况,请立即告诉我们!你可以通过MatrixDiscourse联系我们或者发送邮件到我们的邮件列表mdn-admins list

+{{LearnSidebar}} + +JavaScript 框架是现代前端 web 开发的重要部分,为开发人员提供了构建可伸缩、交互式 web 应用程序的经过测试的工具。许多现代公司使用框架作为工具的标准部分,因此许多前端开发工作现在需要框架经验。 + +作为一个有抱负的前端开发人员,很难找出从哪里开始学习框架——有这么多不同的框架可供选择,新的问题出现,他们大多以类似的方式工作,但做一些不同的事情,还有一些具体的事情时要小心使用框架。 + +在这一系列文章中,我们旨在为您提供一个舒适的起点,帮助您开始学习框架。我们的目标不是详尽地教给你所有你需要知道的关于 React/ReactDOM,或者 Vue,或者其他一些特定的框架;框架团队自己的文档已经完成了这项工作。相反,我们想备份和首先回答更基本的问题,如: + +- 为什么要使用框架?他们为我解决了什么问题? +- 当我尝试选择一个框架时,我应该问什么问题?我甚至需要使用框架吗? +- 框架有什么特性?它们一般是如何工作的?框架对这些特性的实现有何不同? +- 它们与“普通的”JavaScript 或 HTML 有什么关系? + +在此之后,我们将提供一些教程,介绍一些主要框架的基本内容,为您提供足够的上下文和熟悉感,以便您自己开始更深入地学习。我们希望你以一种实用的方式来学习框架,不要忘记 web 平台的基本最佳实践,比如可访问性。 + +**[通过“客户端框架介绍”即刻开始](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction)** + +## 前提条件 + +在尝试学习客户端框架 (HTML、CSS,特别是 JavaScript) 之前,您应该首先真正学习核心 web 语言的基础知识。 + +如果你理解了框架底层的基础 Web 平台特性,你将能编写更加健壮和专业的代码,更容易地排除问题。 + +## 说明指导 + +- [1. 客户端框架介绍](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction) + - : 我们首先从以下话题开始研究框架,框架领域的总览,JavaScript 和框架历史的简介,为什么需要框架以及框架能带给我们什么,如何考虑选择一个框架开始学习,有什么其它的客户端框架可供选择。 +- [2. 框架的主要特性](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features) + - : 每种 JavaScript 框架都有自己不同的方式更新 DOM,处理浏览器事件,为开发者提供愉悦的使用体验,这篇文章将探索“四大”框架的主要特性,从高级角度探讨框架的工作方式以及它们之间的区别。 + +## React 教程 + +> **备注:** React 教程最后测试于 2020 年 5 月,基于 React/ReactDOM 16.13.1 和 create-react-app 3.4.1. +> +> 如果你需要确认你的代码与我们的版本区别,你可以在我们的[todo-react repository](https://github.com/mdn/todo-react)仓库找到 React 应用示例代码的完整版本。想要获取当前最新的版本,查看. + +- [1. 开始使用 React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started) + - : 此章节我们将向 React 打招呼。我们将能发现有关 React 的背景和使用场景的一些细节,在我们的计算机上设置基本的 React 工具链,创建和运行简单的入门应用,学习 React 在这个过程是如何工作的。 +- [2. 开始我们的 React 待办清单](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning) + - : 假设我们计划使用 React 创建 proof-of-concept,一个允许用户添加,编辑和删除工作任务,不删除的情况标记任务完成的应用。此章节将带你完成基本的`App`组件结构和样式,为最后即将添加的独立组件定义和交互做好准备。 +- [3. 组件化我们的 React 应用](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components) + - : 到这个阶段,我们的应用仍是一个单一结构。在让它工作之前,我们需要将它分解为可管理的描述性组件。React 对于组件没有任何硬性规定--这完全取决于你!在此章节我们将向你展示一个合理的方式来将我们的应用分解成 组件。 +- [4. React 交互:事件和状态](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state) + - : 我们的组件化计划已经完成,现在是时候开始将我们的应用从一个完全静态的界面更新成允许交互和变更的界面。在这个章节我们将继续研究事件和状态,借此实现上述功能。 +- [5. React 交互:编辑,过滤,条件渲染](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering) + - : 我们已经接近 React 旅程的终点(至少目前是这样),我们将对我们的 Todo 列表应用的主要功能区域做最后的更改。这包括允许编辑现有的任务,在所有列表,已完成列表和未完成列表中过滤任务。在这个过程中我们将研究条件渲染。 +- [6. React 的可访问性支持](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility) + - : 在我们最后的教程章节,我们将重点介绍可访问性,包括 React 的焦点管理,这可以提高可用性,降低纯键盘用户和屏幕阅读器用户的困扰。 +- [7. React 资源](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources) + - : 我们的最后章节提供了一个 React 资源列表,供你用于进一步的学习。 + +## Ember 教程 + +> **备注:** Ember 教程最后测试于 2020 年 5 月,基于 Ember/Ember CLI version 3.18.0. +> +> 如果你需要确认你的代码与我们的版本区别,你可以在[ember-todomvc-tutorial repository](https://github.com/NullVoxPopuli/ember-todomvc-tutorial/tree/master/steps/00-finished-todomvc/todomvc)找到 Ember 应用示例代码的完整版本。想要获取当前最新的版本,查看 (这还包含了本教程未覆盖到的一些额外的特性)。 + +- [1. 开始使用 Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started) + - : 在我们的 Ember 第一章节中我们将了解 Ember 的工作原理及其用途,本地安装 Ember 工具链,创建一个示例应用,然后做一些初始化设置以便开始开发。 +- [2. Ember 应用结构和组件化](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization) + - : 在此章节,我们将继续规划我们的 TodoMVC Ember 应用,为其添加 HTML 部分,随后将这些 HTML 分解为组件。 +- [3. Ember 交互:事件,类和状态](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state) + - : 至此,我们将添加一些交互行为到我们的应用,使其能够添加和显示新的待办事项。在此过程中,我们将研究如何在 Ember 中使用事件,创建包含 JavaScript 代码的组件类来控制交互功能,并且设置服务来跟踪我们的应用的数据状态。 +- [4. Ember 交互:页脚功能,条件渲染](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer) + - : 现在是时候开始在我们的应用中处理页脚功能了。这里我们将更新待办事项计数器以正确显示待完成待办事项的数量,并正确地为已完成事项应用样式(i.e. 对应列表项的复选框处于选中状态)。我们还将实装我们的“Clear completed”按钮。在这个过程中,我们将学习在我们的模板中使用条件渲染。 +- [5. Ember 路由](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing) + - : 在此章节我们学习路由,有时也称为 URL-based 过滤。我们将使用它来为三个待办视图------"All","Active"和"Completed"提供全局唯一的 URL。 +- [6. Ember 资源和疑难解答](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources) + - : 我们的最后一个 Ember 章节提供了一个供你进一步学习的资源列表,还有一些有用的疑难解答和其他信息。 + +## Vue 教程 + +> **备注:** Vue 教程最后测试于 2020 年 5 月,基于 Vue 2.6.11. +> +> 如果你需要确认你的代码与我们的版本区别,你可以在[todo-vue repository](https://github.com/mdn/todo-vue)找到 Vue 应用示例代码的完整版本。想要获取当前当前最新的版本,查看. + +- [1. 开始使用 Vue](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started) + - : 现在让我们开始介绍 Vue,我们的第三个框架。在此章节我们将简单了解 Vue 的背景,学习如何安装 Vue 以及如何创建一个新项目,学习整个项目的高级架构以及独立的组件,了解如何在本地运行这个项目,并准备开始构建我们的示例。 +- [2. 创建我们的第一个 Vue 组件](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component) + - : 现在是时候深入 Vue,创建我们自己的自定义组件了--我们将从创建一个用来展示待办列表项目的组件开始。在这个过程中,我们将学习一些重要的概念例如在一个组件中调用另一个组件,通过 props 传递数据给另一个组件并保存数据状态。 +- [3. 渲染 Vue 组件列表](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists) + - : 至此我们已经得到了一个完全可用的组件,我们现在已经准备好添加多个`ToDoItem` 组件到我们的应用中了。在此章节我们将了解如何添加一组待办项数据到我们的`App.vue`组件,这组数据我们随后使用`v-for`指令将它们循环并显示到`ToDoItem`组件中。 +- [4. 添加一个新的待办表单:Vue 事件,方法和模型](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models) + - : 现在我们的应用已经有了示例数据和一个循环来将每条数据渲染到`ToDoItem`中。下一步我们要做的是让用户能够输入他们自己的待办事项到这个应用中。 为此我们需要一个文本输入框``,一个在数据提交时触发的事件,一个在数据提交时被触发来添加数据和渲染列表的方法和一个用来控制数据的模型。这就是这个章节我们将要介绍的内容。 +- [5. 使用 CSS 美化 Vue 组件](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling) + - : 终于到了美化我们的应用的时间了。在此章节我们将探索用 CSS 美化 Vue 组件的不同方法。 +- [6. 使用 Vue 计算属性](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties) + - : 在这个章节我们将添加一个显示已完成待办项目数量的计数器,使用 Vue 的一个叫做计算属性的特性。计算属性与方法相似,但是只有它的依赖内容变更时才会再次运作。 +- [7. Vue 条件渲染:编辑既有待办项](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering) + - : 现在是时候加入我们还未实现一个主要功能部分了------编辑既有待办项。为了实现这个功能,我们将利用 Vue 的条件渲染能力------`v-if`和`v-else`来使既有待办项目在查看状态和文本编辑状态之间切换。我们还将添加删除待办项的功能。 +- [8. 使用 Vue refs 进行焦点管理](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management) + - : 我们快要完成 Vue 的使用了。最后要看的一个功能是焦点管理,换种说法,如何改善我们的应用的键盘可操作性。我们将解决这个问题,通过 Vue refs------一个允许你直接操作虚拟 DOM 的底层 DOM,或在组件中直接操作其子组件内部 DOM 结构的高级特性。 +- [9. Vue 资源](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources) + - : 我们将提供一个你可以用来进一步学习的资源列表来圆满结束我们的 Vue 学习教程,从这个列表中你也可以获取一些有用的技巧。 + +## 我们应该选择哪个框架? + +我们在这里发布专注于主要三大框架的系列说明文章------React/ReactDOM,Ember 和 Vue 的一些原因如下: + +- 它们在今后的一段时间内都将是最受欢迎的选择------就像使用任何软件工具一样,依附于一个处于活跃开发状态并且不太会突然停止开发的工具是一个明智的选择,并且它们会成为你寻找工作时所需的技能之一。 +- 它们拥有强大的社区和良好的文档支持。学习复杂的主题时得到帮助是很重要的,特别是你是刚开始学习时。 +- 我们没有资源能覆盖所有现代框架。维护所有现代框架的最新列表是非常困难的,因为总有新的框架在不断被创造出来。 +- 作为一个初学者,在大量的可选内容中选择关注哪部分是很难的,维持一个相对短的列表反而是有益的。 + +我们想在前面说一下------我们**没有**因为我们认为它们是最好的或者我们赞同它们而选择这些我们正在关注的框架。我们只是认为它们在上面这些方面评价比较高。 + +值得一提的是我们也希望在我们的初版发布时能够包含更多框架的内容,但是我们最终决定先把初版内容发布出来随后在此基础上再慢慢添加更多框架内容,而不是延后更长的时间。如果你最喜欢的框架没有包含在这部分内容中而且你想帮助改善这个情况,请立即告诉我们!你可以通过[Matrix](https://wiki.mozilla.org/Matrix)或[Discourse](https://discourse.mozilla.org/c/mdn)联系我们或者发送邮件到我们的邮件列表[mdn-admins list](mailto:mdn-admins@mozilla.org)。 diff --git a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/main_features/index.md b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/main_features/index.md index 82a4d10bd3a30d..506a472a4f2431 100644 --- a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/main_features/index.md +++ b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/main_features/index.md @@ -3,278 +3,315 @@ title: 框架的主要特性 slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features --- -
{{LearnSidebar}}
+{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}} -
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
- -

每种 JavaScript 框架都有自己不同的方式更新 DOM,处理浏览器事件,为开发者提供愉快的使用体验,这篇文章将探索“四大”框架的主要特性,从高级角度探讨框架的工作方式以及它们之间的区别。

+每种 JavaScript 框架都有自己不同的方式更新 DOM,处理浏览器事件,为开发者提供愉快的使用体验,这篇文章将探索“四大”框架的主要特性,从高级角度探讨框架的工作方式以及它们之间的区别。 - - - - - - - - - - + + + + + + + + + +
先决条件:熟悉核心的 HTML, CSSJavaScript 语言。
目标:了解框架主要代码的特性。
先决条件: + 熟悉核心的 HTML, + CSS 和 + JavaScript 语言。 +
目标:了解框架主要代码的特性。
-

Domain-specific languages

+## Domain-specific languages -

All of the frameworks discussed in this module are powered by JavaScript, and all allow you to use domain-specific languages (DSLs) in order to build your applications. In particular, React has popularized the use of JSX for writing its components, while Ember utilizes Handlebars. Unlike HTML, these languages know how to read data variables, and this data can be used to streamline the process of writing your UI.

+All of the frameworks discussed in this module are powered by JavaScript, and all allow you to use domain-specific languages (DSLs) in order to build your applications. In particular, React has popularized the use of **JSX** for writing its components, while Ember utilizes **Handlebars**. Unlike HTML, these languages know how to read data variables, and this data can be used to streamline the process of writing your UI. -

Angular apps often make heavy use of TypeScript. TypeScript is not concerned with the writing of user interfaces, but it is a domain-specific language, and has significant differences to vanilla JavaScript.

+Angular apps often make heavy use of **TypeScript**. TypeScript is not concerned with the writing of user interfaces, but it is a domain-specific language, and has significant differences to vanilla JavaScript. -

DSLs can't be read by the browser directly; they must be transformed into JavaScript or HTML first. Transformation is an extra step in the development process, but framework tooling generally includes the required tools to handle this step, or can be adjusted to include this step. While it is possible to build framework apps without using these domain-specific languages, embracing them will streamline your development process and make it easier to find help from the communities around those frameworks.

+DSLs can't be read by the browser directly; they must be transformed into JavaScript or HTML first. [Transformation is an extra step in the development process](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Overview#Transformation), but framework tooling generally includes the required tools to handle this step, or can be adjusted to include this step. While it is possible to build framework apps without using these domain-specific languages, embracing them will streamline your development process and make it easier to find help from the communities around those frameworks. -

JSX

+### JSX -

JSX, which stands for JavaScript and XML, is an extension of JavaScript that brings HTML-like syntax to a JavaScript environment. It was invented by the React team for use in React applications, but can be used to develop other applications — like Vue apps, for instance.

+[JSX](https://reactjs.org/docs/introducing-jsx.html), which stands for JavaScript and XML, is an extension of JavaScript that brings HTML-like syntax to a JavaScript environment. It was invented by the React team for use in React applications, but can be used to develop other applications — like Vue apps, for instance. -

The following shows a simple JSX example:

+The following shows a simple JSX example: -
const subject = "World";
+```js
+const subject = "World";
 const header = (
-  <header>
-    <h1>Hello, {subject}!</h1>
-  </header>
-);
+
+

Hello, {subject}!

+
+); +``` -

This expression represents an HTML <header> element with a <h1> element inside. The curly braces around subject on line 4 tell the application to read the value of the subject constant and insert it into our <h1>.

+This expression represents an HTML [`
`](/en-US/docs/Web/HTML/Element/header) element with a [`

`](/en-US/docs/Web/HTML/Element/Heading_Elements) element inside. The curly braces around `subject` on line 4 tell the application to read the value of the `subject` constant and insert it into our `

`. -

When used with React, the JSX from the previous snippet would be compiled into this:

+When used with React, the JSX from the previous snippet would be compiled into this: -
var subject = "World";
+```js
+var subject = "World";
 var header = React.createElement("header", null,
   React.createElement("h1", null, "Hello, ", subject, "!")
-);
+); +``` -

When ultimately rendered by the browser, the above snippet will produce HTML that looks like this:

+When ultimately rendered by the browser, the above snippet will produce HTML that looks like this: -
<header>
-  <h1>Hello, World!</h1>
-</header>
+```html +
+

Hello, World!

+
+``` -

Handlebars

+### Handlebars -

The Handlebars templating language is not specific to Ember applications, but it is heavily utilized in Ember apps. Handlebars code resembles HTML, but it has the option of pulling data in from elsewhere. This data can be used to influence the HTML that an application ultimately builds.

+The [Handlebars](https://handlebarsjs.com/) templating language is not specific to Ember applications, but it is heavily utilized in Ember apps. Handlebars code resembles HTML, but it has the option of pulling data in from elsewhere. This data can be used to influence the HTML that an application ultimately builds. -

Like JSX, Handlebars uses curly braces to inject the value of a variable. Handlebars uses a double-pair of curly braces, instead of a single pair.

+Like JSX, Handlebars uses curly braces to inject the value of a variable. Handlebars uses a double-pair of curly braces, instead of a single pair. -

Given this Handlebars template:

+Given this Handlebars template: -
<header>
-  <h1>Hello, \{{subject}}!</h1>
-</header>
+```html +
+

Hello, \{{subject}}!

+
+``` -

And this data:

+And this data: -
{
+```js
+{
   subject: "World"
-}
+} +``` -

Handlebars will build HTML like this:

+Handlebars will build HTML like this: -
<header>
-  <h1>Hello, World!</h1>
-</header>
+```html +
+

Hello, World!

+
+``` -

TypeScript

+### TypeScript -

TypeScript is a superset of JavaScript, meaning it extends JavaScript — all JavaScript code is valid TypeScript, but not the other way around. TypeScript is useful for the strictness it allows developers to enforce on their code. For instance, consider a function add(), which takes integers a and b and returns their sum.

+[TypeScript](https://www.typescriptlang.org/) is a _superset_ of JavaScript, meaning it extends JavaScript — all JavaScript code is valid TypeScript, but not the other way around. TypeScript is useful for the strictness it allows developers to enforce on their code. For instance, consider a function `add()`, which takes integers `a` and `b` and returns their sum. -

In JavaScript, that function could be written like this:

+In JavaScript, that function could be written like this: -
function add(a, b) {
+```js
+function add(a, b) {
   return a + b;
-}
+} +``` -

This code might be trivial for someone accustomed to JavaScript, but it could still be clearer. JavaScript lets us use the + operator to concatenate strings together, so this function would technically still work if a and b were strings — it just might not give you the result you'd expect. What if we wanted to only allow numbers to be passed into this function? TypeScript makes that possible:

+This code might be trivial for someone accustomed to JavaScript, but it could still be clearer. JavaScript lets us use the `+` operator to concatenate strings together, so this function would technically still work if `a` and `b` were strings — it just might not give you the result you'd expect. What if we wanted to only allow numbers to be passed into this function? TypeScript makes that possible: -
function add(a: number, b: number) {
+```js
+function add(a: number, b: number) {
   return a + b;
-}
+} +``` -

The : number written after each parameter here tells TypeScript that both a and b must be numbers. If we were to use this function and pass '2' into it as an argument, TypeScript would raise an error during compilation, and we would be forced to fix our mistake. We could write our own JavaScript that raises these errors for us, but it would make our source code significantly more verbose. It probably makes more sense to let TypeScript handle such checks for us.

+The `: number` written after each parameter here tells TypeScript that both `a` and `b` must be numbers. If we were to use this function and pass `'2'` into it as an argument, TypeScript would raise an error during compilation, and we would be forced to fix our mistake. We could write our own JavaScript that raises these errors for us, but it would make our source code significantly more verbose. It probably makes more sense to let TypeScript handle such checks for us. -

Writing components

+## Writing components -

As mentioned in the previous chapter, most frameworks have some kind of component model. React components can be written with JSX, Ember components with Handlebars, and Angular and Vue components with a templating syntax that lightly extends HTML.

+As mentioned in the previous chapter, most frameworks have some kind of component model. React components can be written with JSX, Ember components with Handlebars, and Angular and Vue components with a templating syntax that lightly extends HTML. -

Regardless of their opinions on how components should be written, each framework's components offer a way to describe the external properties they may need, the internal state that the component should manage, and the events a user can trigger on the component's markup.

+Regardless of their opinions on how components should be written, each framework's components offer a way to describe the external properties they may need, the internal state that the component should manage, and the events a user can trigger on the component's markup. -

The code snippets in the rest of this section will use React as an example, and are written with JSX.

+The code snippets in the rest of this section will use React as an example, and are written with JSX. -

Properties

+### Properties -

Properties, or props, are external data that a component needs in order to render. Suppose you're building a website for an online magazine, and you need to be sure that each contributing writer gets credit for their work. You might create an AuthorCredit component to go with each article. This component needs to display a portrait of the author and a short byline about them. In order to know what image to render, and what byline to print, AuthorCredit needs to accept some props.

+Properties, or **props**, are external data that a component needs in order to render. Suppose you're building a website for an online magazine, and you need to be sure that each contributing writer gets credit for their work. You might create an `AuthorCredit` component to go with each article. This component needs to display a portrait of the author and a short byline about them. In order to know what image to render, and what byline to print, `AuthorCredit` needs to accept some props. -

A React representation of this AuthorCredit component might look something like this:

+A React representation of this `AuthorCredit` component might look something like this: -
function AuthorCredit(props) {
+```js
+function AuthorCredit(props) {
   return (
-    <figure>
-      <img src={props.src} alt={props.alt} />
-      <figcaption>{props.byline}</figcaption>
-    </figure>
+    
+ {props.alt} +
{props.byline}
+
); -}
+} +``` -

{props.src}, {props.alt}, and {props.byline} represent where our props will be inserted into the component. To render this component, we would write code like this in the place where we want it rendered (which will probably be inside another component):

+`{props.src}`, `{props.alt}`, and `{props.byline}` represent where our props will be inserted into the component. To render this component, we would write code like this in the place where we want it rendered (which will probably be inside another component): -
<AuthorCredit
+```js
+
+/>
+```
 
-

This will ultimately render the following <figure> element in the browser, with its structure as defined in the AuthorCredit component, and its content as defined in the props included on the AuthorCredit component call:

+This will ultimately render the following [`
`](/en-US/docs/Web/HTML/Element/figure) element in the browser, with its structure as defined in the `AuthorCredit` component, and its content as defined in the props included on the `AuthorCredit` component call: -
<figure>
-  <img
+```html
+
+ Portrait of Zelda Schiff +
Zelda Schiff is editor-in-chief of the Library Times. - </figcaption> -</figure>
+ +
+``` -

State

+### State -

We talked about the concept of state in the previous chapter — a robust state-handling mechanism is key to an effective framework, and each component may have data that needs its state controlled. This state will persist in some way as long as the component is in use. Like props, state can be used to affect how a component is rendered.

+We talked about the concept of **state** in the previous chapter — a robust state-handling mechanism is key to an effective framework, and each component may have data that needs its state controlled. This state will persist in some way as long as the component is in use. Like props, state can be used to affect how a component is rendered. -

As an example, consider a button that counts how many times it has been clicked. This component should be responsible for tracking its own count state, and could be written like this:

+As an example, consider a button that counts how many times it has been clicked. This component should be responsible for tracking its own _count_ state, and could be written like this: -
function CounterButton() {
+```js
+function CounterButton() {
   const [count] = useState(0);
   return (
-    <button>Clicked {count} times</button>
+    
   );
-}
+} +``` -

useState() is a React hook which, given an initial data value, will keep track of that value as it is updated. The code will be initially rendered like so in the browser:

+[`useState()`](https://reactjs.org/docs/hooks-reference.html#usestate) is a **[React hook](https://reactjs.org/docs/hooks-intro.html)** which, given an initial data value, will keep track of that value as it is updated. The code will be initially rendered like so in the browser: -
<button>Clicked 0 times</button>
+```html + +``` -

The useState() call keeps track of the count value in a robust way across the app, without you needing to write code to do that yourself.

+The `useState()` call keeps track of the `count` value in a robust way across the app, without you needing to write code to do that yourself. -

Events

+### Events -

In order to be interactive, components need ways to respond to browser events, so our applications can respond to our users. Frameworks each provide their own syntax for listening to browser events, which reference the names of the equivalent native browser events.

+In order to be interactive, components need ways to respond to browser events, so our applications can respond to our users. Frameworks each provide their own syntax for listening to browser events, which reference the names of the equivalent native browser events. -

In React, listening for the click event requires a special property, onClick. Let’s update our CounterButton code from above to allow it to count clicks:

+In React, listening for the [`click`](/en-US/docs/Web/API/Element/click_event) event requires a special property, `onClick`. Let’s update our `CounterButton` code from above to allow it to count clicks: -
function CounterButton() {
+```js
+function CounterButton() {
   const [count, setCount] = useState(0);
   return (
-    <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
+    
   );
-}
+} +``` -

In this version we are using additional useState() functionality to create a special setCount() function, which we can invoke to update the value of count. We call this function on line 4, and set count to whatever its current value is, plus one.

+In this version we are using additional `useState()` functionality to create a special `setCount()` function, which we can invoke to update the value of `count`. We call this function on line 4, and set `count` to whatever its current value is, plus one. -

Styling components

+## Styling components -

Each framework offers a way to define styles for your components — or for the application as a whole. Although each framework’s approach to defining the styles of a component is slightly different, all of them give you multiple ways to do so. With the addition of some helper modules, you can style your framework apps in Sass or Less, or transpile your CSS stylesheets with PostCSS.

+Each framework offers a way to define styles for your components — or for the application as a whole. Although each framework’s approach to defining the styles of a component is slightly different, all of them give you multiple ways to do so. With the addition of some helper modules, you can style your framework apps in [Sass](https://sass-lang.com/) or [Less](http://lesscss.org/), or transpile your CSS stylesheets with [PostCSS](https://postcss.org/). -

Handling dependencies

+## Handling dependencies -

All major frameworks provide mechanisms for handling dependencies — using components inside other components, sometimes with multiple hierarchy levels. As with other features, the exact mechanism will differ between frameworks, but the end result is the same. Components tend to import components into other components using the standard JavaScript module syntax, or at least something similar.

+All major frameworks provide mechanisms for handling dependencies — using components inside other components, sometimes with multiple hierarchy levels. As with other features, the exact mechanism will differ between frameworks, but the end result is the same. Components tend to import components into other components using the standard [JavaScript module syntax](/en-US/docs/Web/JavaScript/Guide/Modules), or at least something similar. -

Components in components

+### Components in components -

One key benefit of component-based UI architecture is that components can be composed together. Just like you can write HTML tags inside each other to build a website, you can use components inside other components to build a web application. Each framework allows you to write components that utilize (and thus depend on) other components.

+One key benefit of component-based UI architecture is that components can be composed together. Just like you can write HTML tags inside each other to build a website, you can use components inside other components to build a web application. Each framework allows you to write components that utilize (and thus depend on) other components. -

For example, our AuthorCredit React component might be utilized inside an Article component. That means that Article would need to import AuthorCredit.

+For example, our `AuthorCredit` React component might be utilized inside an `Article` component. That means that `Article` would need to import `AuthorCredit`. -
import AuthorCredit from "./components/AuthorCredit";
+```js +import AuthorCredit from "./components/AuthorCredit"; +``` -

Once that’s done, AuthorCredit could be used inside the Article component like this:

+Once that’s done, `AuthorCredit` could be used inside the `Article` component like this: -
  ...
+```js
+  ...
 
-<AuthorCredit />
+
 
-  ...
+ ... +``` -

Dependency injection

+### Dependency injection -

Real-world applications can often involve component structures with multiple levels of nesting. An AuthorCredit component nested many levels deep might, for some reason, need data from the very root level of our application.

+Real-world applications can often involve component structures with multiple levels of nesting. An `AuthorCredit` component nested many levels deep might, for some reason, need data from the very root level of our application. -

Let's say that the magazine site we're building is structured like this:

+Let's say that the magazine site we're building is structured like this: -
<App>
-  <Home>
-    <Article>
-      <AuthorCredit {/* props */} />
-    </Article>
-  </Home>
-</App>
+```js + + +
+ +
+
+
+``` -

Our App component has data that our AuthorCredit component needs. We could rewrite Home and Article so that they know to pass props down, but this could get tedious if there are many, many levels between the origin and destination of our data. It's also excessive: Home and Article don’t actually make use of the author's portrait or byline, but if we want to get that information into the AuthorCredit, we will need to change Home and Author to accommodate it.

+Our `App` component has data that our `AuthorCredit` component needs. We could rewrite `Home` and `Article` so that they know to pass props down, but this could get tedious if there are many, many levels between the origin and destination of our data. It's also excessive: `Home` and `Article` don’t actually make use of the author's portrait or byline, but if we want to get that information into the `AuthorCredit`, we will need to change `Home` and `Author` to accommodate it. -

The problem of passing data through many layers of components is called prop drilling, and it’s not ideal for large applications.

+The problem of passing data through many layers of components is called prop drilling, and it’s not ideal for large applications. -

To circumvent prop drilling, frameworks provide functionality known as dependency injection, which is a way to get certain data directly to the components that need it, without passing it through intervening levels. Each framework implements dependency injection under a different name, and in a different way, but the effect is ultimately the same.

+To circumvent prop drilling, frameworks provide functionality known as dependency injection, which is a way to get certain data directly to the components that need it, without passing it through intervening levels. Each framework implements dependency injection under a different name, and in a different way, but the effect is ultimately the same. -

Angular calls this process dependency injection; Vue has provide() and inject() component methods; React has a Context API; Ember shares state through services.

+Angular calls this process [dependency injection](https://angular.io/guide/dependency-injection); Vue has [`provide()` and `inject()` component methods](https://vuejs.org/v2/api/#provide-inject); React has a [Context API](https://reactjs.org/docs/context.html); Ember shares state through [services](https://guides.emberjs.com/release/services/). -

Lifecycle

+### Lifecycle -

In the context of a framework, a component’s lifecycle is a collection of phases a component goes through from the time it is rendered by the browser (often called mounting) to the time that it is removed from the DOM (often called unmounting). Each framework names these lifecycle phases differently, and not all give developers access to the same phases. All of the frameworks follow the same general model: they allow developers to perform certain actions when the component mounts, when it renders, when it unmounts, and at many phases in between these.

+In the context of a framework, a component’s **lifecycle** is a collection of phases a component goes through from the time it is rendered by the browser (often called _mounting_) to the time that it is removed from the DOM (often called _unmounting_). Each framework names these lifecycle phases differently, and not all give developers access to the same phases. All of the frameworks follow the same general model: they allow developers to perform certain actions when the component _mounts_, when it _renders_, when it _unmounts_, and at many phases in between these. -

The render phase is the most crucial to understand, because it is repeated the most times as your user interacts with your application. It's run every time the browser needs to render something new, whether that new information is an addition to what's in the browser, a deletion, or an edit of what’s there.

+The _render_ phase is the most crucial to understand, because it is repeated the most times as your user interacts with your application. It's run every time the browser needs to render something new, whether that new information is an addition to what's in the browser, a deletion, or an edit of what’s there. -

This diagram of a React component's lifecycle offers a general overview of the concept.

+This [diagram of a React component's lifecycle](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/) offers a general overview of the concept. -

Rendering elements

+## Rendering elements -

Just as with lifecycles, frameworks take different-but-similar approaches to how they render your applications. All of them track the current rendered version of your browser's DOM, and each makes slightly different decisions about how the DOM should change as components in your application re-render. Because frameworks make these decisions for you, you typically don't interact with the DOM yourself. This abstraction away from the DOM is more complex and more memory-intensive than updating the DOM yourself, but without it, frameworks could not allow you to program in the declarative way they’re known for.

+Just as with lifecycles, frameworks take different-but-similar approaches to how they render your applications. All of them track the current rendered version of your browser's DOM, and each makes slightly different decisions about how the DOM should change as components in your application re-render. Because frameworks make these decisions for you, you typically don't interact with the DOM yourself. This abstraction away from the DOM is more complex and more memory-intensive than updating the DOM yourself, but without it, frameworks could not allow you to program in the declarative way they’re known for. -

The Virtual DOM is an approach whereby information about your browser's DOM is stored in JavaScript memory. Your application updates this copy of the DOM, then compares it to the "real" DOM — the DOM that is actually rendered for your users — in order to decide what to render. The application builds a "diff" to compare the differences between the updated virtual DOM and the currently rendered DOM, and uses that diff to apply updates to the real DOM. Both React and Vue utilize a virtual DOM model, but they do not apply the exact same logic when diffing or rendering.

+The **Virtual DOM** is an approach whereby information about your browser's DOM is stored in JavaScript memory. Your application updates this copy of the DOM, then compares it to the "real" DOM — the DOM that is actually rendered for your users — in order to decide what to render. The application builds a "diff" to compare the differences between the updated virtual DOM and the currently rendered DOM, and uses that diff to apply updates to the real DOM. Both React and Vue utilize a virtual DOM model, but they do not apply the exact same logic when diffing or rendering. -

You can read more about the Virtual DOM in the React docs.

+You can [read more about the Virtual DOM in the React docs](https://reactjs.org/docs/faq-internals.html#what-is-the-virtual-dom). -

The Incremental DOM is similar to the virtual DOM in that it builds a DOM diff to decide what to render, but different in that it doesn't create a complete copy of the DOM in JavaScript memory. It ignores the parts of the DOM that do not need to be changed. Angular is the only framework discussed so far in this module that uses an incremental DOM.

+The **Incremental DOM** is similar to the virtual DOM in that it builds a DOM diff to decide what to render, but different in that it doesn't create a complete copy of the DOM in JavaScript memory. It ignores the parts of the DOM that do not need to be changed. Angular is the only framework discussed so far in this module that uses an incremental DOM. -

You can read more about the Incremental DOM on the Auth0 blog.

+You can [read more about the Incremental DOM on the Auth0 blog](https://auth0.com/blog/incremental-dom/). -

The Glimmer VM is unique to Ember. It is not a virtual DOM nor an incremental DOM; it is a separate process through which Ember's templates are transpiled into a kind of "byte code" that is easier and faster to read than JavaScript.

+The **Glimmer VM** is unique to Ember. It is not a virtual DOM nor an incremental DOM; it is a separate process through which Ember's templates are transpiled into a kind of "byte code" that is easier and faster to read than JavaScript. -

Routing

+## Routing -

As mentioned in the previous chapter, routing is an important part of the web experience. To avoid a broken experience in sufficiently complex apps with lots of views, each of the frameworks covered in this module provides a library (or more than one library) that helps developers implement client-side routing in their applications.

+As [mentioned in the previous chapter, routing](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction#Routing) is an important part of the web experience. To avoid a broken experience in sufficiently complex apps with lots of views, each of the frameworks covered in this module provides a library (or more than one library) that helps developers implement client-side routing in their applications. -

Testing

+## Testing -

All applications benefit from test coverage that ensures your software continues to behave in the way that you'd expect, and web applications are no different. Each framework's ecosystem provides tooling that facilitates the writing of tests. Testing tools are not built into the frameworks themselves, but the command-line interface tools used to generate framework apps give you access to the appropriate testing tools.

+All applications benefit from test coverage that ensures your software continues to behave in the way that you'd expect, and web applications are no different. Each framework's ecosystem provides tooling that facilitates the writing of tests. Testing tools are not built into the frameworks themselves, but the command-line interface tools used to generate framework apps give you access to the appropriate testing tools. -

Each framework has extensive tools in its ecosystem, with capabilities for unit and integration testing alike.

+Each framework has extensive tools in its ecosystem, with capabilities for unit and integration testing alike. -

Testing Library is a suite of testing utilities that has tools for many JavaScript environments, including React, Vue, and Angular. The Ember docs cover the testing of Ember apps.

+[Testing Library](https://testing-library.com/) is a suite of testing utilities that has tools for many JavaScript environments, including React, Vue, and Angular. The Ember docs cover the [testing of Ember apps](https://guides.emberjs.com/release/testing/). -

Here’s a quick test for our CounterButton written with the help of React Testing Library — it tests a number of things, such as the button's existence, and whether the button is displaying the correct text after being clicked 0, 1, and 2 times:

+Here’s a quick test for our `CounterButton` written with the help of React Testing Library — it tests a number of things, such as the button's existence, and whether the button is displaying the correct text after being clicked 0, 1, and 2 times: -
import React from "react";
+```js
+import React from "react";
 import { render, fireEvent } from "@testing-library/react";
 import "@testing-library/jest-dom/extend-expect";
 
 import CounterButton from "./CounterButton";
 
-it("renders a semantic with an initial state of 0", () => {
-  const { getByRole } = render(<CounterButton />);
+it("renders a semantic with an initial state of 0", () => {
+  const { getByRole } = render();
   const btn = getByRole("button");
 
   expect(btn).toBeInTheDocument();
   expect(btn).toHaveTextContent("Clicked 0 times");
 });
 
-it("Increments the count when clicked", () => {
-  const { getByRole } = render(<CounterButton />);
+it("Increments the count when clicked", () => {
+  const { getByRole } = render();
   const btn = getByRole("button");
 
   fireEvent.click(btn);
@@ -282,73 +319,63 @@ it("Increments the count when clicked", () => {
 
   fireEvent.click(btn);
   expect(btn).toHaveTextContent("Clicked 2 times");
-});
- -

Summary

- -

At this point you should have more of an idea about the actual languages, features, and tools you'll be using as you create applications with frameworks. I'm sure you’re enthusiastic to get going and actually do some coding, and that's what you are going to do next! At this point you can choose which framework you'd like to start learning first:

- - - -
-

备注: We only have three framework tutorial series available now, but we hope to have more available in the future.

-
- -

{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}

- -

In this module

- - +}); +``` + +## Summary + +At this point you should have more of an idea about the actual languages, features, and tools you'll be using as you create applications with frameworks. I'm sure you’re enthusiastic to get going and actually do some coding, and that's what you are going to do next! At this point you can choose which framework you'd like to start learning first: + +- [React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started) +- [Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started) +- [Vue](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started) + +> **备注:** We only have three framework tutorial series available now, but we hope to have more available in the future. + +{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}} + +## In this module + +- [Introduction to client-side frameworks](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction) +- [Framework main features](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features) +- React + + - [Getting started with React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started) + - [Beginning our React todo list](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning) + - [Componentizing our React app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components) + - [React interactivity: Events and state](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state) + - [React interactivity: Editing, filtering, conditional rendering](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering) + - [Accessibility in React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility) + - [React resources](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources) + +- Ember + + - [Getting started with Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started) + - [Ember app structure and componentization](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization) + - [Ember interactivity: Events, classes and state](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state) + - [Ember Interactivity: Footer functionality, conditional rendering](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer) + - [Routing in Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing) + - [Ember resources and troubleshooting](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources) + +- Vue + + - [Getting started with Vue](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started) + - [Creating our first Vue component](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component) + - [Rendering a list of Vue components](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists) + - [Adding a new todo form: Vue events, methods, and models](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models) + - [Styling Vue components with CSS](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling) + - [Using Vue computed properties](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties) + - [Vue conditional rendering: editing existing todos](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering) + - [Focus management with Vue refs](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management) + - [Vue resources](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources) + +- Svelte + + - [Getting started with Svelte](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started) + - [Starting our Svelte Todo list app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning) + - [Dynamic behavior in Svelte: working with variables and props](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props) + - [Componentizing our Svelte app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components) + - [Advanced Svelte: Reactivity, lifecycle, accessibility](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility) + - [Working with Svelte stores](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores) + - [TypeScript support in Svelte](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript) + - [Deployment and next steps](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next) diff --git a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_components/index.md b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_components/index.md index 242967d6396ce5..35d74fa0139e7a 100644 --- a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_components/index.md +++ b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_components/index.md @@ -3,448 +3,484 @@ title: Componentizingapp slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components --- -
{{LearnSidebar}}
+{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}} -
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
- -

At this point, our app is a monolith. Before we can make it do things, we need to break it apart into manageable, descriptive components. React doesn’t have any hard rules for what is and isn’t a component – that’s up to you! In this article we will show you a sensible way to break our app up into components.

+At this point, our app is a monolith. Before we can make it do things, we need to break it apart into manageable, descriptive components. React doesn’t have any hard rules for what is and isn’t a component – that’s up to you! In this article we will show you a sensible way to break our app up into components. - - - - - - - - - - + + + + + + + + + +
Prerequisites: -

Familiarity with the core HTML, CSS, and JavaScript languages, knowledge of the terminal/command line.

-
Objective:To show a sensible way of breaking our todo list app into components.
Prerequisites: +

+ Familiarity with the core HTML, + CSS, and + JavaScript languages, + knowledge of the + terminal/command line. +

+
Objective: + To show a sensible way of breaking our todo list app into components. +
-

Defining our first component

+## Defining our first component -

Defining a component can seem tricky until you have some practice, but the gist is:

+Defining a component can seem tricky until you have some practice, but the gist is: -
    -
  • If it represents an obvious "chunk" of your app, it's probably a component
  • -
  • If it gets reused often, it's probably a component.
  • -
+- If it represents an obvious "chunk" of your app, it's probably a component +- If it gets reused often, it's probably a component. -

That second bullet is especially valuable: making a component out of common UI elements allows you to change your code in one place and see those changes everywhere that component is used. You don't have to break everything out into components right away, either. Let's take the second bullet point as inspiration and make a component out of the most reused, most important piece of the UI: a todo list item.

+That second bullet is especially valuable: making a component out of common UI elements allows you to change your code in one place and see those changes everywhere that component is used. You don't have to break everything out into components right away, either. Let's take the second bullet point as inspiration and make a component out of the most reused, most important piece of the UI: a todo list item. -

Make a <Todo />

+## Make a `` -

Before we can make a component, we should create a new file for it. In fact, we should make a directory just for our components. The following commands make a components directory and then, within that, a file called Todo.js. Make sure you're in the root of your app before you run these!

+Before we can make a component, we should create a new file for it. In fact, we should make a directory just for our components. The following commands make a `components` directory and then, within that, a file called `Todo.js`. Make sure you're in the root of your app before you run these! -
mkdir src/components
-touch src/components/Todo.js
+```bash +mkdir src/components +touch src/components/Todo.js +``` -

Our new Todo.js file is currently empty! Open it up and give it its first line:

+Our new `Todo.js` file is currently empty! Open it up and give it its first line: -
import React from "react";
+```js +import React from "react"; +``` -

Since we're going to make a component called Todo, you can start adding the code for that to Todo.js too, as follows. In this code, we define the function and export it on the same line:

+Since we're going to make a component called `Todo`, you can start adding the code for that to `Todo.js` too, as follows. In this code, we define the function and export it on the same line: -
export default function Todo() {
+```js
+export default function Todo() {
   return (
 
   );
-}
+} +``` -

This is OK so far, but our component has to return something! Go back to src/App.js, copy the first <li> from inside the unordered list, and paste it into Todo.js so that it reads like this:

+This is OK so far, but our component has to return something! Go back to `src/App.js`, copy the first [`
  • `](/en-US/docs/Web/HTML/Element/li) from inside the unordered list, and paste it into `Todo.js` so that it reads like this: -
    export default function Todo() {
    +```js
    +export default function Todo() {
       return (
    -    <li className="todo stack-small">
    -      <div className="c-cb">
    -        <input id="todo-0" type="checkbox" defaultChecked={true} />
    -        <label className="todo-label" htmlFor="todo-0">
    +    
  • +
    + + +
    +
    + + +
    +
  • ); -}
    +} +``` -
    -

    备注: Components must always return something. If at any point in the future you try to render a component that does not return anything, React will display an error in your browser.

    -
    +> **备注:** Components must always return something. If at any point in the future you try to render a component that does not return anything, React will display an error in your browser. -

    Our Todo component is complete, at least for now; now we can use it. In App.js, add the following line near the top of the file to import Todo:

    +Our `Todo` component is complete, at least for now; now we can use it. In `App.js`, add the following line near the top of the file to import `Todo`: -
    import Todo from "./components/Todo";
    +```js +import Todo from "./components/Todo"; +``` -

    With this component imported, you can replace all of the <li> elements in App.js with <Todo /> component calls. Your <ul> should read like this:

    +With this component imported, you can replace all of the `
  • ` elements in `App.js` with `` component calls. Your `
      ` should read like this: -
      <ul
      +```js
      +
        +> + + + +
      +``` -

      When you look back at your browser, you'll notice something unfortunate: your list now repeats the first task three times!

      +When you look back at your browser, you'll notice something unfortunate: your list now repeats the first task three times! -

      Our todo list app, with todo components repeating because the label is hardcoded into the component

      +![Our todo list app, with todo components repeating because the label is hardcoded into the component](todo-list-repeating-todos.png) -

      We don't only want to eat; we have other things to — well — to do. Next we'll look at how we can make different component calls render unique content.

      +We don't only want to eat; we have other things to — well — to do. Next we'll look at how we can make different component calls render unique content. -

      Make a unique <Todo />

      +## Make a _unique_ `` -

      Components are powerful because they let us re-use pieces of our UI, and refer to one place for the source of that UI. The problem is, we don't typically want to reuse all of each component; we want to reuse most parts, and change small pieces. This is where props come in.

      +Components are powerful because they let us re-use pieces of our UI, and refer to one place for the source of that UI. The problem is, we don't typically want to reuse all of each component; we want to reuse most parts, and change small pieces. This is where props come in. -

      What's in a name?

      +### What's in a `name`? -

      In order to track the names of tasks we want to complete, we should ensure that each <Todo /> component renders a unique name.

      +In order to track the names of tasks we want to complete, we should ensure that each `` component renders a unique name. -

      In App.js, give each <Todo /> a name prop. Let’s use the names of our tasks that we had before:

      +In `App.js`, give each `` a name prop. Let’s use the names of our tasks that we had before: -
      <Todo name="Eat" />
      -<Todo name="Sleep" />
      -<Todo name="Repeat" />
      +```js + + + +``` -

      When your browser refreshes, you will see… the exact same thing as before. We gave our <Todo /> some props, but we aren't using them yet. Let's go back to Todo.js and remedy that.

      +When your browser refreshes, you will see… the exact same thing as before. We gave our `` some props, but we aren't using them yet. Let's go back to `Todo.js` and remedy that. -

      First modify your Todo() function definition so that it takes props as a parameter. You can console.log() your props as we did before, if you'd like to check that they are being received by the component correctly.

      +First modify your `Todo()` function definition so that it takes `props` as a parameter. You can `console.log()` your `props` as we did before, if you'd like to check that they are being received by the component correctly. -

      Once you're confident that your component is getting its props, you can replace every occurrence of Eat with your name prop. Remember: when you're in the middle of a JSX expression, you use curly braces to inject the value of a variable.

      +Once you're confident that your component is getting its `props`, you can replace every occurrence of `Eat` with your `name` prop. Remember: when you're in the middle of a JSX expression, you use curly braces to inject the value of a variable. -

      Putting all that together, your Todo() function should read like this:

      +Putting all that together, your `Todo()` function should read like this: -
      export default function Todo(props) {
      +```js
      +export default function Todo(props) {
         return (
      -    <li className="todo stack-small">
      -      <div className="c-cb">
      -        <input id="todo-0" type="checkbox" defaultChecked={true} />
      -        <label className="todo-label" htmlFor="todo-0">
      +    
    • +
      + + +
      +
      + + +
      +
    • ); -}
      +} +``` -

      Now your browser should show three unique tasks. Another problem remains though: they're all still checked by default.

      +_Now_ your browser should show three unique tasks. Another problem remains though: they're all still checked by default. -

      Our todo list, with different todo labels now they are passed into the components as props

      +![Our todo list, with different todo labels now they are passed into the components as props](todo-list-unique-todos.png) -

      Is it completed?

      +### Is it `completed`? -

      In our original static list, only Eat was checked. Once again, we want to reuse most of the UI that makes up a <Todo /> component, but change one thing. That's a good job for another prop! Give each <Todo /> call in App.js a new prop of completed. The first (Eat) should have a value of true; the rest should be false:

      +In our original static list, only `Eat` was checked. Once again, we want to reuse _most_ of the UI that makes up a `` component, but change one thing. That's a good job for another prop! Give each `` call in `App.js` a new prop of `completed`. The first (`Eat`) should have a value of `true`; the rest should be `false`: -
      <Todo name="Eat" completed={true} />
      -<Todo name="Sleep" completed={false} />
      -<Todo name="Repeat" completed={false} />
      +```js + + + +``` -

      As before, we must go back to Todo.js to actually use these props. Change the defaultChecked attribute on the <input /> so that its value is equal to the completed prop. Once you’re done, the Todo component's <input /> element will read like this:

      +As before, we must go back to `Todo.js` to actually use these props. Change the `defaultChecked` attribute on the `` so that its value is equal to the `completed` prop. Once you’re done, the Todo component's `` element will read like this: -
      <input id="todo-0" type="checkbox" defaultChecked={props.completed} />
      +```js + +``` -

      And your browser should update to show only Eat being checked:

      +And your browser should update to show only `Eat` being checked: -

      Our todo list app, now with differing checked states - some checkboxes are checked, others not

      +![Our todo list app, now with differing checked states - some checkboxes are checked, others not](todo-list-differing-checked-states.png) -

      If you change each <Todo /> component’s completed prop, your browser will check or uncheck the equivalent rendered checkboxes accordingly.

      +If you change each `` component’s `completed` prop, your browser will check or uncheck the equivalent rendered checkboxes accordingly. -

      Gimme some id, please

      +### Gimme some `id`, please -

      Right now, our <Todo /> component gives every task an id attribute of todo-0. This is bad HTML because id attributes must be unique (they are used as unique identifiers for document fragments, by CSS, JavaScript, etc.). This means we should give our component an id prop that takes a unique value for each Todo.

      +Right now, our `` component gives every task an `id` attribute of `todo-0`. This is bad HTML because [`id` attributes](/en-US/docs/Web/HTML/Global_attributes/id) must be unique (they are used as unique identifiers for document fragments, by CSS, JavaScript, etc.). This means we should give our component an `id` prop that takes a unique value for each `Todo`. -

      To follow the same pattern we had initially, let's give each instance of the <Todo /> component an ID in the format of todo-i, where i gets larger by one every time:

      +To follow the same pattern we had initially, let's give each instance of the `` component an ID in the format of `todo-i`, where `i` gets larger by one every time: -
      <Todo name="Eat" completed={true} id="todo-0" />
      -<Todo name="Sleep" completed={false} id="todo-1" />
      -<Todo name="Repeat" completed={false} id="todo-2" />
      +```js + + + +``` -

      Now go back to Todo.js and make use of the id prop. It needs to replace the value of the id attribute of the <input /> element, as well as the value of its label's htmlFor attribute:

      +Now go back to `Todo.js` and make use of the `id` prop. It needs to replace the value of the `id` attribute of the `` element, as well as the value of its label's `htmlFor` attribute: -
      <div className="c-cb">
      -  <input id={props.id} type="checkbox" defaultChecked={props.completed} />
      -  <label className="todo-label" htmlFor={props.id}>
      +```js
      +
      + +
      + + +``` -

      So far, so good?

      +## So far, so good? -

      We’re making good use of React so far, but we could do better! Our code is repetitive. The three lines that render our <Todo /> component are almost identical, with only one difference: the value of each prop.

      +We’re making good use of React so far, but we could do better! Our code is repetitive. The three lines that render our `` component are almost identical, with only one difference: the value of each prop. -

      We can clean up our code with one of JavaScript's core abilities: iteration. To use iteration, we should first re-think our tasks.

      +We can clean up our code with one of JavaScript's core abilities: iteration. To use iteration, we should first re-think our tasks. -

      Tasks as data

      +## Tasks as data -

      Each of our tasks currently contains three pieces of information: its name, whether it has been checked, and its unique ID. This data translates nicely to an object. Since we have more than one task, an array of objects would work well in representing this data.

      +Each of our tasks currently contains three pieces of information: its name, whether it has been checked, and its unique ID. This data translates nicely to an object. Since we have more than one task, an array of objects would work well in representing this data. -

      In src/index.js, make a new const beneath the final import, but above ReactDOM.render():

      +In `src/index.js`, make a new `const` beneath the final import, but above `ReactDOM.render()`: -
      const DATA = [
      +```js
      +const DATA = [
         { id: "todo-0", name: "Eat", completed: true },
         { id: "todo-1", name: "Sleep", completed: false },
         { id: "todo-2", name: "Repeat", completed: false }
      -];
      +]; +``` -

      Next, we'll pass DATA to <App /> as a prop, called tasks. The final line of src/index.js should read like this:

      +Next, we'll pass `DATA` to `` as a prop, called `tasks`. The final line of `src/index.js` should read like this: -
      ReactDOM.render(<App tasks={DATA} />, document.getElementById("root"));
      +```js +ReactDOM.render(, document.getElementById("root")); +``` -

      This array is now available to the App component as props.tasks. You can console.log() it to check, if you’d like.

      +This array is now available to the App component as `props.tasks`. You can `console.log()` it to check, if you’d like. -
      -

      备注: ALL_CAPS constant names have no special meaning in JavaScript; they’re a convention that tells other developers "this data will never change after being defined here”.

      -
      +> **备注:** `ALL_CAPS` constant names have no special meaning in JavaScript; they’re a convention that tells other developers "this data will never change after being defined here”. -

      Rendering with iteration

      +## Rendering with iteration -

      To render our array of objects, we have to turn each one into a <Todo /> component. JavaScript gives us an array method for transforming data into something else: Array.prototype.map().

      +To render our array of objects, we have to turn each one into a `` component. JavaScript gives us an array method for transforming data into something else: [`Array.prototype.map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). -

      Above the return statement of App(), make a new const called taskList and use map() to transform it. Let's start by turning our tasks array into something simple: the name of each task:

      +Above the return statement of `App()`, make a new `const` called `taskList` and use `map()` to transform it. Let's start by turning our `tasks` array into something simple: the `name` of each task: -
      const taskList = props.tasks.map(task => task.name);
      +```js +const taskList = props.tasks.map(task => task.name); +``` -

      Let’s try replacing all the children of the <ul> with taskList:

      +Let’s try replacing all the children of the `
        ` with `taskList`: -
        <ul
        +```js
        +
          {taskList} -</ul>
        +
      +``` -

      This gets us some of the way towards showing all the components again, but we’ve got more work to do: the browser currently renders each task's name as unstructured text. We’re missing our HTML structure — the <li> and its checkboxes and buttons!

      +This gets us some of the way towards showing all the components again, but we’ve got more work to do: the browser currently renders each task's name as unstructured text. We’re missing our HTML structure — the `
    • ` and its checkboxes and buttons! -

      Our todo list app with the todo item labels just shown bunched up on one line

      +![Our todo list app with the todo item labels just shown bunched up on one line](todo-list-unstructured-names.png) -

      To fix this, we need to return a <Todo /> component from our map() function — remember that JSX allows us to mix up JavaScript and markup structures! Let's try the following instead of what we have already:

      +To fix this, we need to return a `` component from our `map()` function — remember that JSX allows us to mix up JavaScript and markup structures! Let's try the following instead of what we have already: -
       const taskList = props.tasks.map(task => <Todo />);
      +```js + const taskList = props.tasks.map(task => ); +``` -

      Look again at your app; now our tasks look more like they used to, but they’re missing the names of the tasks themselves. Remember that each task we map over has the id, name, and checked properties we want to pass into our <Todo /> component. If we put that knowledge together, we get code like this:

      +Look again at your app; now our tasks look more like they used to, but they’re missing the names of the tasks themselves. Remember that each task we map over has the `id`, `name`, and `checked` properties we want to pass into our `` component. If we put that knowledge together, we get code like this: -
      const taskList = props.tasks.map(task => (
      -  <Todo id={task.id} name={task.name} completed={task.completed} />
      -));
      +```js +const taskList = props.tasks.map(task => ( + +)); +``` -

      Now the app looks like it did before, and our code is less repetitive.

      +Now the app looks like it did before, and our code is less repetitive. -

      Unique keys

      +## Unique keys -

      Now that React is rendering our tasks out of an array, it has to keep track of which one is which in order to render them properly. React tries to do its own guesswork to keep track of things, but we can help it out by passing a key prop to our <Todo /> components. key is a special prop that's managed by React – you cannot use the word key for any other purpose.

      +Now that React is rendering our tasks out of an array, it has to keep track of which one is which in order to render them properly. React tries to do its own guesswork to keep track of things, but we can help it out by passing a `key` prop to our `` components. `key` is a special prop that's managed by React – you cannot use the word `key` for any other purpose. -

      Because keys should be unique, we're going to re-use the id of each task object as its key. Update your taskList constant like so:

      +Because keys should be unique, we're going to re-use the `id` of each task object as its key. Update your `taskList` constant like so: -
      const taskList = props.tasks.map(task => (
      -    <Todo
      +```js
      +const taskList = props.tasks.map(task => (
      +    
         )
      -);
      +); +``` -

      You should always pass a unique key to anything you render with iteration. Nothing obvious will change in your browser, but if you do not use unique keys, React will log warnings to your console and your app may behave strangely!

      +**You should always pass a unique key to anything you render with iteration.** Nothing obvious will change in your browser, but if you do not use unique keys, React will log warnings to your console and your app may behave strangely! -

      Componentizing the rest of the app

      +## Componentizing the rest of the app -

      Now that we've got our most important component sorted out, we can turn the rest of our app into components. Remembering that components are either obvious pieces of UI, or reused pieces of UI, or both, we can make two more components:

      +Now that we've got our most important component sorted out, we can turn the rest of our app into components. Remembering that components are either obvious pieces of UI, or reused pieces of UI, or both, we can make two more components: -
        -
      • <Form/>
      • -
      • <FilterButton/>
      • -
      +- `
      ` +- `` -

      Since we know we need both, we can batch some of the file creation work together with a terminal command. Run this command in your terminal, taking care that you're in the root directory of your app:

      +Since we know we need both, we can batch some of the file creation work together with a terminal command. Run this command in your terminal, taking care that you're in the root directory of your app: -
      touch src/components/Form.js src/components/FilterButton.js
      +```bash +touch src/components/Form.js src/components/FilterButton.js +``` -

      The <Form />

      +### The `` -

      Open components/Form.js and do the following:

      +Open `components/Form.js` and do the following: -
        -
      • Import React at the top of the file, like we did in Todo.js.
      • -
      • Make yourself a new Form() component with the same basic structure as Todo(), and export that component.
      • -
      • Copy the <form> tags and everything between them from inside App.js, and paste them inside Form()’s return statement.
      • -
      • Export Form at the end of the file.
      • -
      +- Import `React` at the top of the file, like we did in `Todo.js`. +- Make yourself a new `Form()` component with the same basic structure as `Todo()`, and export that component. +- Copy the `` tags and everything between them from inside `App.js`, and paste them inside `Form()`’s `return` statement. +- Export `Form` at the end of the file. -

      Your Form.js file should read like this:

      +Your `Form.js` file should read like this: -
      import React from "react";
      +```js
      +import React from "react";
       
       function Form(props) {
         return (
      -    <form>
      -      <h2 className="label-wrapper">
      -        <label htmlFor="new-todo-input" className="label__lg">
      +    
      +      

      + +

      + + + ); } -export default Form;
      +export default Form; +``` -

      The <FilterButton />

      +### The \ -

      Do the same things you did to create Form.js inside FilterButton.js, but call the component FilterButton() and copy the HTML for the first button inside the <div> element with the class of filters from App.js into the return statement.

      +Do the same things you did to create `Form.js` inside `FilterButton.js`, but call the component `FilterButton()` and copy the HTML for the first button inside the `
      ` element with the `class` of `filters` from `App.js` into the `return` statement. -

      The file should read like this:

      +The file should read like this: -
      import React from "react";
      +```js
      +import React from "react";
       
       function FilterButton(props) {
         return (
      -    <button type="button" className="btn toggle-btn" aria-pressed="true">
      -      <span className="visually-hidden">Show </span>
      -      <span>all </span>
      -      <span className="visually-hidden"> tasks</span>
      -    </button>
      +    
         );
       }
       
      -export default FilterButton;
      +export default FilterButton; +``` -
      -

      备注: You might notice that we are making the same mistake here as we first made for the <Todo /> component, in that each button will be the same. That’s fine! We’re going to fix up this component later on, in Back to the filter buttons.

      -
      +> **备注:** You might notice that we are making the same mistake here as we first made for the `` component, in that each button will be the same. That’s fine! We’re going to fix up this component later on, in [Back to the filter buttons](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering#Back_to_the_filter_buttons). -

      Importing all our components

      +## Importing all our components -

      Let's make use of our new components.

      +Let's make use of our new components. -

      Add some more import statements to the top of App.js, to import them.

      +Add some more `import` statements to the top of `App.js`, to import them. -

      Then, update the return statement of App() so that it renders our components. When you’re done, App.js will read like this:

      +Then, update the `return` statement of `App()` so that it renders our components. When you’re done, `App.js` will read like this: -
      import React from "react";
      +```js
      +import React from "react";
       import Form from "./components/Form";
       import FilterButton from "./components/FilterButton";
       import Todo from "./components/Todo";
       
       function App(props) {
      -  const taskList = props.tasks.map(task => (
      -    <Todo
      +  const taskList = props.tasks.map(task => (
      +    
           )
         );
         return (
      -    <div className="todoapp stack-large">
      -      <Form />
      -      <div className="filters btn-group stack-exception">
      -        <FilterButton />
      -        <FilterButton />
      -        <FilterButton />
      -      </div>
      -      <h2 id="list-heading">3 tasks remaining</h2>
      -      <ul
      +    
      +
      +
      + + + +
      +

      3 tasks remaining

      +
        {taskList} - </ul> - </div> +
      +
      ); } -export default App;
      - -

      With this in place, we’re almost ready to tackle some interactivity in our React app!

      - -

      Summary

      - -

      And that's it for this article — we've gone into some depth on how to break up your app nicely into components, end render them efficiently. Now we'll go on to look at how we handle events in React, and start adding some interactivity.

      - -

      {{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}

      - -

      In this module

      - - +export default App; +``` + +With this in place, we’re _almost_ ready to tackle some interactivity in our React app! + +## Summary + +And that's it for this article — we've gone into some depth on how to break up your app nicely into components, end render them efficiently. Now we'll go on to look at how we handle events in React, and start adding some interactivity. + +{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}} + +## In this module + +- [Introduction to client-side frameworks](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction) +- [Framework main features](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features) +- React + + - [Getting started with React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started) + - [Beginning our React todo list](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning) + - [Componentizing our React app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components) + - [React interactivity: Events and state](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state) + - [React interactivity: Editing, filtering, conditional rendering](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering) + - [Accessibility in React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility) + - [React resources](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources) + +- Ember + + - [Getting started with Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started) + - [Ember app structure and componentization](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization) + - [Ember interactivity: Events, classes and state](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state) + - [Ember Interactivity: Footer functionality, conditional rendering](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer) + - [Routing in Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing) + - [Ember resources and troubleshooting](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources) + +- Vue + + - [Getting started with Vue](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started) + - [Creating our first Vue component](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component) + - [Rendering a list of Vue components](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists) + - [Adding a new todo form: Vue events, methods, and models](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models) + - [Styling Vue components with CSS](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling) + - [Using Vue computed properties](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties) + - [Vue conditional rendering: editing existing todos](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering) + - [Focus management with Vue refs](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management) + - [Vue resources](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources) + +- Svelte + + - [Getting started with Svelte](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started) + - [Starting our Svelte Todo list app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning) + - [Dynamic behavior in Svelte: working with variables and props](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props) + - [Componentizing our Svelte app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components) + - [Advanced Svelte: Reactivity, lifecycle, accessibility](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility) + - [Working with Svelte stores](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores) + - [TypeScript support in Svelte](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript) + - [Deployment and next steps](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next) diff --git a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_getting_started/index.md b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_getting_started/index.md index 590a81319ba340..160f66ad7da52d 100644 --- a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_getting_started/index.md +++ b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_getting_started/index.md @@ -12,141 +12,157 @@ tags: translation_of: >- Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started --- -
      {{LearnSidebar}}
      +{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}} -
      {{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
      - -

      本文会引导我们进入一段 React 学习之旅。我们将逐步了解有关它的背景和用例的一些细节,在自己的电脑上建起基本的 React 工具链,创建并使用一个简单的入门应用程序,以学习一些关于 React 在此过程中如何工作的知识。

      +本文会引导我们进入一段 React 学习之旅。我们将逐步了解有关它的背景和用例的一些细节,在自己的电脑上建起基本的 React 工具链,创建并使用一个简单的入门应用程序,以学习一些关于 React 在此过程中如何工作的知识。 - - - - - - - - - - + + + + + + + + + +
      先决条件: -

      熟悉核心 HTMLCSSJavaScript 语言,了解终端/命令行

      - -

      React 使用称为 JSX(JavaScript 和 XML)的 HTML-in-JavaScript 语法。熟悉 HTML 和 JavaScript 可以帮助您学习 JSX,并更好地确定应用程序中的错误是与 JavaScript 还是与 React 的更特定领域相关。

      -
      目的:要设置本地 React 开发环境,创建一个启动应用程序,并了解其工作原理
      先决条件: +

      + 熟悉核心 HTMLCSS + 和 JavaScript 语言,了解终端/命令行。 +

      +

      + React 使用称为 JSX(JavaScript 和 XML)的 HTML-in-JavaScript + 语法。熟悉 HTML 和 JavaScript 可以帮助您学习 + JSX,并更好地确定应用程序中的错误是与 JavaScript 还是与 React + 的更特定领域相关。 +

      +
      目的:要设置本地 React 开发环境,创建一个启动应用程序,并了解其工作原理
      -

      你好 React

      - -

      如其官方口号所示,React 是一个用于构建用户界面的库。React 不是一个框架 —— 它的应用甚至不局限于 Web 开发,它可以与其他库一起使用以渲染到特定环境。例如,React Native 可用于构建移动应用程序;React 360 可用于构建虚拟现实应用程序……

      +## 你好 React -

      为了构建 Web 应用,开发人员将 React 与 ReactDOM 结合使用。React 和 ReactDOM 通常被与其他真正的 Web 开发框架相提并论,并用于解决相同的问题。当我们将 React 称为“框架”时,就是在进行口语化的理解。

      +如其官方口号所示,[React](https://reactjs.org/) 是一个用于构建用户界面的库。React 不是一个框架 —— 它的应用甚至不局限于 Web 开发,它可以与其他库一起使用以渲染到特定环境。例如,[React Native](https://reactnative.dev/) 可用于构建移动应用程序;[React 360](https://facebook.github.io/react-360/) 可用于构建虚拟现实应用程序…… -

      React 的主要目标是最大程度地减少开发人员构建 UI 时发生的错误。它通过使用组件——描述部分用户界面的、自包含的逻辑代码段——来实现此目的。这些组件可以组合在一起以创建完整的 UI,React 将许多渲染工作进行抽象化,使您可以专注于 UI 设计 (译者注:显而易见,此设计不等于视觉稿的设计)。

      +为了构建 Web 应用,开发人员将 React 与 [ReactDOM 结合使用](https://reactjs.org/docs/react-dom.html)。React 和 ReactDOM 通常被与其他真正的 Web 开发框架相提并论,并用于解决相同的问题。当我们将 React 称为“框架”时,就是在进行口语化的理解。 -

      用例

      +React 的主要目标是最大程度地减少开发人员构建 UI 时发生的错误。它通过使用组件——描述部分用户界面的、自包含的逻辑代码段——来实现此目的。这些组件可以组合在一起以创建完整的 UI,React 将许多渲染工作进行抽象化,使您可以专注于 UI 设计 (译者注:显而易见,此设计不等于视觉稿的设计)。 -

      与本模块中涵盖的其他框架不同,React 不会对代码约定或文件组织实施严格的规则。这使团队可以设置最适合自己的约定,并以他们希望的任何方式采用 React。React 可以处理一个按钮,一个界面的几个部分或应用程序的整个用户界面。

      +## 用例 -

      尽管 React 可以用于界面的小片段中,但要和 jQuery 这样的库,甚至是像 Vue 这样的框架那样“引入”应用程序并不容易 —— 当你使用 React 构建整个应用程序时更容易上手。

      +与本模块中涵盖的其他框架不同,React 不会对代码约定或文件组织实施严格的规则。这使团队可以设置最适合自己的约定,并以他们希望的任何方式采用 React。React 可以处理一个按钮,一个界面的几个部分或应用程序的整个用户界面。 -

      另外,许多开发人员的经验对于 React 应用程序也是有用处的,例如使用 JSX 编写界面是需要编译过程的。在网站上添加类似于 Babel 的编译器会让网站上代码的运行速度变慢,因此开发人员通常会在构建项目的时候设置这样的工具。React 对于工具的要求可以说是很高的,但这是能够学习解决的。

      +尽管 React 可以用于[界面的小片段](https://reactjs.org/docs/add-react-to-a-website.html)中,但要和 jQuery 这样的库,甚至是像 Vue 这样的框架那样“引入”应用程序并不容易 —— 当你使用 React 构建整个应用程序时更容易上手。 -

      本文将重点介绍使用 React 通过 Facebook 的 create-react-app 内的工具渲染应用程序中整个用户界面的用例。

      +另外,许多开发人员的经验对于 React 应用程序也是有用处的,例如使用 JSX 编写界面是需要编译过程的。在网站上添加类似于 Babel 的编译器会让网站上代码的运行速度变慢,因此开发人员通常会在构建项目的时候设置这样的工具。React 对于工具的要求可以说是很高的,但这是能够学习解决的。 -

      React 如何使用 JavaScript?

      +本文将重点介绍使用 React 通过 Facebook 的 [create-react-app](https://create-react-app.dev/) 内的工具渲染应用程序中整个用户界面的用例。 -

      React 中的许多模式都使用了现代 JavaScript 的功能。React 与 JavaScript 的最大区别在于 JSX 语法的使用上。JSX 是在 JavaScript 语法上的拓展,因此类似于 HTML 的代码可以和 JSX 共存。例如:

      +## React 如何使用 JavaScript? -
      const heading = <h1>Mozilla Developer Network</h1>;
      +React 中的许多模式都使用了现代 JavaScript 的功能。React 与 JavaScript 的最大区别在于 [JSX](https://reactjs.org/docs/introducing-jsx.html) 语法的使用上。JSX 是在 JavaScript 语法上的拓展,因此类似于 HTML 的代码可以和 JSX 共存。例如: -

      该 heading 常量称为 JSX 表达式。React 可以使用它在我们的应用程序中渲染 <h1> 标签。

      +```js +const heading =

      Mozilla Developer Network

      ; +``` -

      假设出于语义原因,我们想将 heading 包装 <header> 在标记中?JSX 方法允许我们将元素彼此嵌套,就像使用 HTML 一样:

      +该 heading 常量称为 **JSX 表达式**。React 可以使用它在我们的应用程序中渲染 [`

      `](/en-US/docs/Web/HTML/Element/Heading_Elements) 标签。 -
      const header = (
      -  <header>
      -    <h1>Mozilla Developer Network</h1>
      -  </header>
      -);
      +假设出于语义原因,我们想将 heading 包装 [`
      `](/en-US/docs/Web/HTML/Element/header) 在标记中?JSX 方法允许我们将元素彼此嵌套,就像使用 HTML 一样: -
      -

      备注: 上一个代码段中的括号并非 JSX 的一部分,它对您的应用程序没有任何影响,括号只是用来向您(和您的计算机)表明其中的多行代码属于同一个表达式 (译者注:原文表述实在有点啰嗦)。因此上面的代码等同于:

      +```js +const header = ( +
      +

      Mozilla Developer Network

      +
      +); +``` -
      const header = <header>
      -    <h1>Mozilla Developer Network</h1>
      -</header>
      +> **备注:** 上一个代码段中的括号并非 JSX 的一部分,它对您的应用程序没有任何影响,括号只是用来向您(和您的计算机)表明其中的多行代码属于同一个表达式 (译者注:原文表述实在有点啰嗦)。因此上面的代码等同于: +> +> ```js +> const header =
      +>

      Mozilla Developer Network

      +>
      +> ``` +> +> 这看起来多少有点不适感,因为表达式前面的 [`
      `](/en-US/docs/Web/HTML/Element/header) 标记没有缩进与其对应的结束标记相同的位置。 -

      这看起来多少有点不适感,因为表达式前面的 <header> 标记没有缩进与其对应的结束标记相同的位置。

      -
      +浏览器是无法读取直接解析 JSX 的。我们的 header 表达式经过( [Babel](https://babeljs.io/) 或 [Parcel](https://parceljs.org/) 之类的工具)编译之后是这样的: -

      浏览器是无法读取直接解析 JSX 的。我们的 header 表达式经过( BabelParcel 之类的工具)编译之后是这样的:

      - -
      const header = React.createElement("header", null,
      +```js
      +const header = React.createElement("header", null,
         React.createElement("h1", null, "Mozilla Developer Network")
      -);
      - -

      可以跳过编译步骤,并使用 React.createElement() 自己编写 UI。但是,这样做会失去 JSX 的声明性优势,并且代码变得更难以阅读。编译是开发过程中的一个额外步骤,但是 React 社区中的许多开发人员都认为 JSX 的可读性值得。另外,流行的工具使 JSX-to-JavaScript 编译成为其设置过程的一部分。除非您愿意,否则不必自己配置编译。

      +); +``` -

      由于 JSX 是 HTML 和 JavaScript 的结合,因此一些开发人员认为它很直观。其他人则说它的混合特性使它变得混乱。但是,一旦熟悉了它,它将使您能够更快,更直观地构建用户界面,并使其他人一眼就能更好地理解您的代码库。

      +*可以*跳过编译步骤,并使用 [`React.createElement()`](https://reactjs.org/docs/react-api.html#createelement) 自己编写 UI。但是,这样做会失去 JSX 的声明性优势,并且代码变得更难以阅读。编译是开发过程中的一个额外步骤,但是 React 社区中的许多开发人员都认为 JSX 的可读性值得。另外,流行的工具使 JSX-to-JavaScript 编译成为其设置过程的一部分。除非您愿意,否则不必自己配置编译。 -

      要阅读有关 JSX 的更多信息,请查看 React 团队的 JSX In Depth 文章。

      +由于 JSX 是 HTML 和 JavaScript 的结合,因此一些开发人员认为它很直观。其他人则说它的混合特性使它变得混乱。但是,一旦熟悉了它,它将使您能够更快,更直观地构建用户界面,并使其他人一眼就能更好地理解您的代码库。 -

      设置您的第一个 React 应用

      +要阅读有关 JSX 的更多信息,请查看 React 团队的 [JSX In Depth](https://reactjs.org/docs/jsx-in-depth.html) 文章。 -

      有很多使用 React 的方法,但是我们将使用命令行界面(CLI)工具 create-react-app,如前所述,该方法通过安装一些软件包并创建一些软件包来加快开发 React 应用程序的过程。文件供您处理上述工具。

      +## 设置您的第一个 React 应用 -

      通过将一些 <script> 元素复制到 HTML 文件中,可以在没有 create-react-app 的情况下将 React 添加到网站,但是 create-react-app CLI 是 React 应用程序的常见起点。使用它可以让您花费更多的时间来构建应用,而花更少的时间进行设置。

      +有很多使用 React 的方法,但是我们将使用命令行界面(CLI)工具 create-react-app,如前所述,该方法通过安装一些软件包并创建一些软件包来加快开发 React 应用程序的过程。文件供您处理上述工具。 -

      要求

      +通过将一些 [``部分。在` +``` + +现在我们可以开始为`ToDoItem`添加实际内容了。Vue 模板目前只允许一个根元素--一个元素需要包裹模板内的所有内容(Vue 3 发布后会改变这种情况)。我们将为该根元素使用一个[`
      `](/zh-CN/docs/Web/HTML/Element/div)。 -

      现在我们可以开始为ToDoItem添加实际内容了。Vue 模板目前只允许一个根元素--一个元素需要包裹模板内的所有内容(Vue 3 发布后会改变这种情况)。我们将为该根元素使用一个<div>

      +1. 现在在你的组件模板中添加一个空的`
      `。 +2. 在那个`
      `里面,让我们添加一个`checkbox`和一个对应的`label`。给复选框添加一个`id`,并添加一个`for`属性,将复选框映射到标签上,如下图所示。. -
        -
      1. -

        现在在你的组件模板中添加一个空的<div>

        -
      2. -
      3. -

        在那个<div>里面,让我们添加一个checkbox和一个对应的label。给复选框添加一个id,并添加一个for属性,将复选框映射到标签上,如下图所示。.

        + ```html + + ``` -
        <template>
        -  <div>
        -    <input type="checkbox" id="todo-item" checked="false" />
        -    <label for="todo-item">My Todo Item</label>
        -  </div>
        -</template>
        -
      4. -
      +### 在应用程序中使用 TodoItem 组件 -

      在应用程序中使用 TodoItem 组件

      +这一切都很顺利,但我们还没有将组件添加到我们的应用程序中,所以没有办法测试它,看看一切是否正常。我们现在就把它添加进去吧。 -

      这一切都很顺利,但我们还没有将组件添加到我们的应用程序中,所以没有办法测试它,看看一切是否正常。我们现在就把它添加进去吧。

      +1. 再次打开`App.vue`文件。 +2. 在` +``` -

      使用已注册的 props

      +### 使用已注册的 props -

      随着组件对象中这些 props 的定义,我们可以在 template 里使用这些变量值。让我们开始向组件模版中添加 label prop。

      +随着组件对象中这些 props 的定义,我们可以在 template 里使用这些变量值。让我们开始向组件模版中添加 `label` prop。 -

      在你的 <template> 中,将 <label> 标签的 contents 内容修改为 \{{label}}

      +在你的 `