diff --git a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/index.html b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/index.html deleted file mode 100644 index c04d583fdf9ae1..00000000000000 --- a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: 理解客户端 JavaScript 框架 -slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks -tags: - - JavaScript - - 初学者 - - 前段框架 - - 学习 - - 客户端 -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 教程

- -
-

Note: 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 教程

- -
-

Note: 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 教程

- -
-

Note: 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

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 new file mode 100644 index 00000000000000..a6017dc5174113 --- /dev/null +++ b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/index.md @@ -0,0 +1,118 @@ +--- +title: 理解客户端 JavaScript 框架 +slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks +tags: + - JavaScript + - 初学者 + - 前段框架 + - 学习 + - 客户端 +translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks +--- +{{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.html b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/main_features/index.html deleted file mode 100644 index 10cee9b569a3f6..00000000000000 --- a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/main_features/index.html +++ /dev/null @@ -1,354 +0,0 @@ ---- -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}}
- -
{{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,处理浏览器事件,为开发者提供愉快的使用体验,这篇文章将探索“四大”框架的主要特性,从高级角度探讨框架的工作方式以及它们之间的区别。

- - - - - - - - - - - - -
先决条件:熟悉核心的 HTML, CSSJavaScript 语言。
目标:了解框架主要代码的特性。
- -

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.

- -

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.

- -

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.

- -

The following shows a simple JSX example:

- -
const subject = "World";
-const header = (
-  <header>
-    <h1>Hello, {subject}!</h1>
-  </header>
-);
- -

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>.

- -

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

- -
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:

- -
<header>
-  <h1>Hello, World!</h1>
-</header>
- -

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.

- -

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:

- -
<header>
-  <h1>Hello, \{{subject}}!</h1>
-</header>
- -

And this data:

- -
{
-  subject: "World"
-}
- -

Handlebars will build HTML like this:

- -
<header>
-  <h1>Hello, World!</h1>
-</header>
- -

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.

- -

In JavaScript, that function could be written like this:

- -
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:

- -
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.

- -

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.

- -

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.

- -

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.

- -

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

- -
function AuthorCredit(props) {
-  return (
-    <figure>
-      <img src={props.src} alt={props.alt} />
-      <figcaption>{props.byline}</figcaption>
-    </figure>
-  );
-}
- -

{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
-  src="./assets/zelda.png"
-  alt="Portrait of Zelda Schiff"
-  byline="Zelda Schiff is editor-in-chief of the Library Times."
-/>
- -

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:

- -
<figure>
-  <img
-    src="assets/zelda.png"
-    alt="Portrait of Zelda Schiff"
-  >
-  <figcaption>
-    Zelda Schiff is editor-in-chief of the Library Times.
-  </figcaption>
-</figure>
- -

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.

- -

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() {
-  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:

- -
<button>Clicked 0 times</button>
- -

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

- -

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:

- -
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.

- -

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.

- -

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.

- -

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.

- -

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";
- -

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

- -
  ...
-
-<AuthorCredit />
-
-  ...
- -

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.

- -

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

- -
<App>
-  <Home>
-    <Article>
-      <AuthorCredit {/* props */} />
-    </Article>
-  </Home>
-</App>
- -

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.

- -

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.

- -

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.

- -

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.

- -

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.

- -

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.

- -

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.

- -

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

- -

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.

- -

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.

- -

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.

- -

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";
-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 />);
-  const btn = getByRole("button");
-
-  expect(btn).toBeInTheDocument();
-  expect(btn).toHaveTextContent("Clicked 0 times");
-});
-
-it("Increments the count when clicked", () => {
-  const { getByRole } = render(<CounterButton />);
-  const btn = getByRole("button");
-
-  fireEvent.click(btn);
-  expect(btn).toHaveTextContent("Clicked 1 times");
-
-  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:

- - - -
-

Note: 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

- - 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 new file mode 100644 index 00000000000000..506a472a4f2431 --- /dev/null +++ b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/main_features/index.md @@ -0,0 +1,381 @@ +--- +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}}{{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,处理浏览器事件,为开发者提供愉快的使用体验,这篇文章将探索“四大”框架的主要特性,从高级角度探讨框架的工作方式以及它们之间的区别。 + + + + + + + + + + + + +
先决条件: + 熟悉核心的 HTML, + CSS 和 + JavaScript 语言。 +
目标:了解框架主要代码的特性。
+ +## 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. + +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](/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](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: + +```js +const subject = "World"; +const header = ( +
+

Hello, {subject}!

+
+); +``` + +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: + +```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: + +```html +
+

Hello, World!

+
+``` + +### Handlebars + +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. + +Given this Handlebars template: + +```html +
+

Hello, \{{subject}}!

+
+``` + +And this data: + +```js +{ + subject: "World" +} +``` + +Handlebars will build HTML like this: + +```html +
+

Hello, World!

+
+``` + +### TypeScript + +[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: + +```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: + +```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. + +## 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. + +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. + +### 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. + +A React representation of this `AuthorCredit` component might look something like this: + +```js +function AuthorCredit(props) { + return ( +
+ {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): + +```js + +``` + +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: + +```html +
+ Portrait of Zelda Schiff +
+ Zelda Schiff is editor-in-chief of the Library Times. +
+
+``` + +### 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. + +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: + +```js +function CounterButton() { + const [count] = useState(0); + return ( + + ); +} +``` + +[`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: + +```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. + +### 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`](/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: + +```js +function CounterButton() { + const [count, setCount] = useState(0); + return ( + + ); +} +``` + +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 + +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 + +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 + +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`. + +```js +import AuthorCredit from "./components/AuthorCredit"; +``` + +Once that’s done, `AuthorCredit` could be used inside the `Article` component like this: + +```js + ... + + + + ... +``` + +### 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. + +Let's say that the magazine site we're building is structured like this: + +```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. + +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. + +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 + +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. + +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 + +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. + +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. + +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. + +## Routing + +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 + +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. + +[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: + +```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(); + const btn = getByRole("button"); + + expect(btn).toBeInTheDocument(); + expect(btn).toHaveTextContent("Clicked 0 times"); +}); + +it("Increments the count when clicked", () => { + const { getByRole } = render(); + const btn = getByRole("button"); + + fireEvent.click(btn); + expect(btn).toHaveTextContent("Clicked 1 times"); + + 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: + +- [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.html b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_components/index.html deleted file mode 100644 index 91bb19e04c42d8..00000000000000 --- a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_components/index.html +++ /dev/null @@ -1,450 +0,0 @@ ---- -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}}
- -
{{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.

- - - - - - - - - - - - -
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 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.
  • -
- -

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 />

- -

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
- -

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

- -
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:

- -
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:

- -
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">
-          Eat
-        </label>
-      </div>
-      <div className="btn-group">
-        <button type="button" className="btn">
-          Edit <span className="visually-hidden">Eat</span>
-        </button>
-        <button type="button" className="btn btn__danger">
-          Delete <span className="visually-hidden">Eat</span>
-        </button>
-      </div>
-    </li>
-  );
-}
- -
-

Note: 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:

- -
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:

- -
<ul
-  role="list"
-  className="todo-list stack-large stack-exception"
-  aria-labelledby="list-heading"
->
-  <Todo />
-  <Todo />
-  <Todo />
-</ul>
- -

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

- -

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 />

- -

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?

- -

In order to track the names of tasks we want to complete, we should ensure that each <Todo /> 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:

- -
<Todo name="Eat" />
-<Todo name="Sleep" />
-<Todo name="Repeat" />
- -

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.

- -

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.

- -

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

- -
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">
-          {props.name}
-        </label>
-      </div>
-      <div className="btn-group">
-        <button type="button" className="btn">
-          Edit <span className="visually-hidden">{props.name}</span>
-        </button>
-        <button type="button" className="btn btn__danger">
-          Delete <span className="visually-hidden">{props.name}</span>
-        </button>
-      </div>
-    </li>
-  );
-}
- -

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

- -

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:

- -
<Todo name="Eat" completed={true} />
-<Todo name="Sleep" completed={false} />
-<Todo name="Repeat" completed={false} />
- -

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:

- -
<input id="todo-0" type="checkbox" defaultChecked={props.completed} />
- -

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

- -

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

- -

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.

- -

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:

- -
<Todo name="Eat" completed={true} id="todo-0" />
-<Todo name="Sleep" completed={false} id="todo-1" />
-<Todo name="Repeat" completed={false} id="todo-2" />
- -

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:

- -
<div className="c-cb">
-  <input id={props.id} type="checkbox" defaultChecked={props.completed} />
-  <label className="todo-label" htmlFor={props.id}>
-    {props.name}
-  </label>
-</div>
- -

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 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

- -

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():

- -
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:

- -
ReactDOM.render(<App tasks={DATA} />, 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.

- -
-

Note: 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

- -

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().

- -

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);
- -

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

- -
<ul
-  role="list"
-  className="todo-list stack-large stack-exception"
-  aria-labelledby="list-heading"
->
-  {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!

- -

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

- -

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:

- -
 const taskList = props.tasks.map(task => <Todo />);
- -

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:

- -
const taskList = props.tasks.map(task => (
-  <Todo id={task.id} name={task.name} completed={task.completed} />
-));
- -

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

- -

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.

- -

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
-      id={task.id}
-      name={task.name}
-      completed={task.completed}
-      key={task.id}
-    />
-  )
-);
- -

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

- -

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:

- -
touch src/components/Form.js src/components/FilterButton.js
- -

The <Form />

- -

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.
  • -
- -

Your Form.js file should read like this:

- -
import React from "react";
-
-function Form(props) {
-  return (
-    <form>
-      <h2 className="label-wrapper">
-        <label htmlFor="new-todo-input" className="label__lg">
-          What needs to be done?
-        </label>
-      </h2>
-      <input
-        type="text"
-        id="new-todo-input"
-        className="input input__lg"
-        name="text"
-        autoComplete="off"
-      />
-      <button type="submit" className="btn btn__primary btn__lg">
-        Add
-      </button>
-    </form>
-  );
-}
-
-export default Form;
- -

The <FilterButton />

- -

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.

- -

The file should read like this:

- -
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;
- -
-

Note: 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.

-
- -

Importing all our components

- -

Let's make use of our new components.

- -

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:

- -
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
-        id={task.id}
-        name={task.name}
-        completed={task.completed}
-        key={task.id}
-      />
-    )
-  );
-  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
-        role="list"
-        className="todo-list stack-large stack-exception"
-        aria-labelledby="list-heading"
-      >
-        {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

- - 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 new file mode 100644 index 00000000000000..35d74fa0139e7a --- /dev/null +++ b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_components/index.md @@ -0,0 +1,486 @@ +--- +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}}{{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. + + + + + + + + + + + + +
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 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. + +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 `` + +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! + +```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: + +```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: + +```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 [`
  • `](/en-US/docs/Web/HTML/Element/li) from inside the unordered list, and paste it into `Todo.js` so that it reads like this: + +```js +export default function Todo() { + return ( +
  • +
    + + +
    +
    + + +
    +
  • + ); +} +``` + +> **备注:** 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`: + +```js +import Todo from "./components/Todo"; +``` + +With this component imported, you can replace all of the `
  • ` elements in `App.js` with `` component calls. Your `
      ` should read like this: + +```js +
        + + + +
      +``` + +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](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. + +## 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. + +### What's in a `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 `` a name prop. Let’s use the names of our tasks that we had before: + +```js + + + +``` + +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. + +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: + +```js +export default function Todo(props) { + return ( +
    • +
      + + +
      +
      + + +
      +
    • + ); +} +``` + +_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](todo-list-unique-todos.png) + +### 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 `` 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`: + +```js + + + +``` + +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: + +```js + +``` + +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](todo-list-differing-checked-states.png) + +If you change each `` component’s `completed` prop, your browser will check or uncheck the equivalent rendered checkboxes accordingly. + +### Gimme some `id`, please + +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 `` component an ID in the format of `todo-i`, where `i` gets larger by one every time: + +```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 `` element, as well as the value of its label's `htmlFor` attribute: + +```js +
      + + +
      +``` + +## 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 `` 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. + +## 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. + +In `src/index.js`, make a new `const` beneath the final import, but above `ReactDOM.render()`: + +```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 `` as a prop, called `tasks`. The final line of `src/index.js` should read like this: + +```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. + +> **备注:** `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 + +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: + +```js +const taskList = props.tasks.map(task => task.name); +``` + +Let’s try replacing all the children of the `
        ` with `taskList`: + +```js +
          + {taskList} +
        +``` + +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](todo-list-unstructured-names.png) + +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: + +```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 `` component. If we put that knowledge together, we get code like this: + +```js +const taskList = props.tasks.map(task => ( + +)); +``` + +Now the app looks like it did before, and our code is less repetitive. + +## 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 `` 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: + +```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! + +## 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: + +- `
        ` +- `` + +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: + +```bash +touch src/components/Form.js src/components/FilterButton.js +``` + +### The `` + +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 `` 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: + +```js +import React from "react"; + +function Form(props) { + return ( + +

        + +

        + + + + ); +} + +export default Form; +``` + +### 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 `
        ` element with the `class` of `filters` from `App.js` into the `return` statement. + +The file should read like this: + +```js +import React from "react"; + +function FilterButton(props) { + return ( + + ); +} + +export default FilterButton; +``` + +> **备注:** 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 + +Let's make use of our new components. + +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: + +```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 => ( + + ) + ); + return ( +
        +
        +
        + + + +
        +

        3 tasks remaining

        +
          + {taskList} +
        +
        + ); +} + +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.html b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_getting_started/index.html deleted file mode 100644 index c701d9690eb5ee..00000000000000 --- a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_getting_started/index.html +++ /dev/null @@ -1,480 +0,0 @@ ---- -title: React 入门 -slug: >- - Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started -tags: - - JavaScript - - React - - 初学者 - - 学习 - - 客户端 - - 框架 -translation_of: >- - Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started ---- -
        {{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")}}
        - -

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

        - - - - - - - - - - - - -
        先决条件: -

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

        - -

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

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

        你好 React

        - -

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

        - -

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

        - -

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

        - -

        用例

        - -

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

        - -
        -

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

        -
        - -

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

        - -

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

        - -

        React 如何使用 JavaScript?

        - -

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

        - -
        const heading = <h1>Mozilla Developer Network</h1>;
        - -

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

        - -

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

        - -
        const header = (
        -  <header>
        -    <h1>Mozilla Developer Network</h1>
        -  </header>
        -);
        - -
        -

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

        - -
        const header = <header>
        -    <h1>Mozilla Developer Network</h1>
        -</header>
        - -

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

        -
        - -

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

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

        - -

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

        - -

        设置您的第一个 React 应用

        - -

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

        - -

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

        - -

        要求

        - -

        为了使用 create-react-app,您需要安装 Node.js。建议您使用长期支持(LTS)版本。Node 包括 npm(Node 程序包管理器)和 npx(Node 程序包运行器)

        - -

        您也可以使用 Yarn 软件包管理器作为替代方案,但是我们假设在这套教程中使用 npm。有关 npm 和 yarn 的更多信息,请参见程序包管理基础

        - -

        如果您使用的是 Windows,则需要安装一些软件以与 Unix/macOS 终端保持同等地位,才能使用本教程中提到的终端命令。Gitbash(作为 git Windows 工具集的一部分提供)或适用于 Linux 的 Windows 子系统WSL)均适用。有关这些以及一般终端命令的更多信息,请参见命令行速成课程

        - -

        还请记住,React 和 ReactDOM 生成的应用程序只能在相当现代的一组浏览器上运行 —— 通过某些 polyfill 可以使用 IE9+。在阅读这些教程时,建议您使用 Firefox,Safari 或 Chrome 等现代浏览器。

        - -

        另外,有关更多信息,请参见以下内容:

        - - - -

        初始化您的应用

        - -

        create-react-app ,该命令接受一个参数:即你想给自己的应用所起的名字。create-react-app 将为此应用创建一个同名的文件夹,并在其中创建所需文件。在你打算放置你的应用程序的文件夹下打开你的命令终端,并键入命令:

        - -
        npx create-react-app moz-todo-react
        - -

        这句命令创建了一个名为 moz-todo-react 的文件夹, 并在此文件夹里做了如下工作:

        - -
          -
        • 为你的应用程序安装了一些 npm 包;
        • -
        • 写入 react 应用启动所需要的脚本文件;
        • -
        • 创建一系列结构化的子文件夹和文件,奠定应用程序的基础架构;
        • -
        • 如果你的电脑上安装了 git 的话,顺便帮你把 git 仓库也建好。
        • -
        - -
        -

        备注:如果你的电脑上安装了 yarn 的话,create-react-app 会默认使用 yarn 而非 npm。如果你同时安装了 yarn 和 npm,但你希望使用 npm 的话,在 create-react-app 的时候需要输入 --use-npm :

        - -
        npx create-react-app moz-todo-react --use-npm
        -
        - -

        create-react-app 运行的时候会在终端上显示一些与其状态相关的信息,通常情况下无需为此担心。运行需要一点时间,在此期间你可以适度放松一下。

        - -

        处理完成之后,你可以 cdmoz-todo-react 文件夹下,然后键入 npm start 命令并回车,先前由 create-react-app 创建的脚本会启动一个地服务 localhost:3000,并打开你的默认浏览器来访问这个服务。成功启动浏览器的话,你的浏览器上会显示如下画面:

        - -

        Firefox MacOS的屏幕截图,打开到localhost:3000,显示了默认的create-react-app应用程序

        - -

        应用结构

        - -

        create-react-app 提供了开发 React 应用所需的工具。它的初始文件结构如下:

        - -
        moz-todo-react
        -├── README.md
        -├── node_modules
        -├── package.json
        -├── package-lock.json
        -├── .gitignore
        -├── public
        -│   ├── favicon.ico
        -│   ├── index.html
        -│   └── manifest.json
        -└── src
        -    ├── App.css
        -    ├── App.js
        -    ├── App.test.js
        -    ├── index.css
        -    ├── index.js
        -    ├── logo.svg
        -    └── serviceWorker.js
        - -

        目录 src 是我们花费时间最多的地方,因为它是我们 React 应用源码存放的目录。

        - -

        目录 public 包含了开发应用时浏览器会读取的文件,其中最重要的就是 index.html。React 将目录 src 中的代码嵌入这个文件,从而浏览器才能运行此文件。 index.html中的有些内容关乎 create-react-app 的运作,因此除非你知道自己在做什么样的修改,否则不建议编辑这个文件。当然,你可以修改index.html中的 <title> 元素的内容来表现此应用程序通俗易懂的名称。

        - -

        目录 public 会在建立并部署此应用的时候更新。此教程不涉及部署,你可以参考 Deploying our app 这一篇教程。

        - -

        文件 package.json 包含了 Node.js/npm 为了建立该应用程序所管理着的文件信息。这个文件不是 React 应用独有的。你无需理解这个文件也能看懂这篇教程。 不过,如果你想了解更多,你可以阅读 What is the file `package.json`? on NodeJS.orgPackage management basics

        - -

        探索第一个 React 组件 — <App/>

        - -

        在 React 中,组件是组成应用程序的可重复利用的模块。组件可大可小,但它们都只有单一的、明确的功能。

        - -

        打开 src/App.js,之前打开的页面也提示我们对这个文件进行编辑。这个文件包含了我们第一个组件 App,内容如下:

        - -
        import React from 'react';
        -import logo from './logo.svg';
        -import './App.css';
        -
        -function App() {
        -  return (
        -    <div className="App">
        -      <header className="App-header">
        -        <img src={logo} className="App-logo" alt="logo" />
        -        <p>
        -          Edit <code>src/App.js</code> and save to reload.
        -        </p>
        -        <a
        -          className="App-link"
        -          href="https://reactjs.org"
        -          target="_blank"
        -          rel="noopener noreferrer"
        -        >
        -          Learn React
        -        </a>
        -      </header>
        -    </div>
        -  );
        -}
        -export default App;
        - -

        文件 App.js 主要由三部分组成: 顶部的 import 语句,中间的 App 组件,以及底部的 export 语句。大多数 React 组件都遵循这个模式。

        - -

        import 语句

        - -

        脚本开头的 import 语句允许在此脚本中使用其他文件中的代码,让我们更进一步地了解这些语句。

        - -
        import React from 'react';
        -import logo from './logo.svg';
        -import './App.css';
        - -

        第一句代码引入了 React 库,这是为了将代码中的 JSX 语句转为React.createElement(),所有的 React 模块都应该引入 React 模块,否则会抛错。

        - -

        第二句代码引入了 './logo.svg'。注意文件路径以 ./ 开头、由 .svg 尾——表明这是一个本地文件,并且它不是 JavaScript 文件。

        - -
        -

        我们没有指定 React 模块的路径——表明它并非来自本地文件,而是在 package.json 文件中列为依赖项。在整个学习过程中,请务必留心这两种引入方式的不同之处。

        -
        - -

        第三行引入了我们的组件所需的 CSS 文件。与上面两句不同,这里没有将引入的内容赋给任何变量、也没有用到 from 指令。请注意这种特殊的语法并非原生 JS 的语法 —— 它源自前端资源打包工具 webpack,而 create-react-app 正是基于 webpack 配置而来的。

        - -
        -

        译者补充:webpack 可用于打包 JS 和非 JS 的内容 (当然,非 JS 的内容需要一些插件或加载器来处理),但是 JavaScript 标准只有关于 JS 的内容,所以 webpack 社区使用这种特殊的 `import` 语句来声明对非 JS 内容的引用。

        - -

        详情参见 webpack 官方和社区,截止目前 (2020 年下旬),webpack 仍是现代前端工作中必不可少的技能之一。

        -
        - -

        App 组件

        - -

        在 import 所需资源之后,我们定义了一个名为 App 的函数,尽管大部分 JavaScript 社区推崇使用驼峰式命名法,如:“helloWorld”。但 React 组件使用帕斯卡命名法,如“HelloWorld”,来帮助用户辨认一个 JSX 元素是 React 组件而非普通的 HTML 标签。如果您将函数名“App”改为“app”,您的浏览器会显示错误。

        - -

        让我们进一步看下 App 方法。

        - -
        function App() {
        -  return (
        -    <div className="App">
        -      <header className="App-header">
        -        <img src={logo} className="App-logo" alt="logo" />
        -        <p>
        -          Edit <code>src/App.js</code> and save to reload.
        -        </p>
        -        <a
        -          className="App-link"
        -          href="https://reactjs.org"
        -          target="_blank"
        -          rel="noopener noreferrer"
        -        >
        -          Learn React
        -        </a>
        -      </header>
        -    </div>
        -  );
        -}
        - -

        App 方法返回一个 JSX 表达式,这个表达式定义了浏览器最终要渲染的 DOM。

        - -

        表达式中的元素就像以前写的 HTML 一样,都拥有属性,并且遵循 attribute="value" 的模式。在第三行,开始标签 <div> 有着 className 属性。这个属性与在 HTML 中的 class 属性相同,但是由于 JSX 就是 JavaScript, 我们不能使用 class 属性 - 这个是关键字,意味着 JavaScript 已经用它执行其它任务,使用 class 属性将会在我们的代码中产生冲突。由于同样的原因,一些其它的 HTML 属性在 JSX 中也有着不同的书写方式,当我们碰到它们时,我们将会详述。

        - -

        把第 6 行的 <p> 标签内容改为 "Hello, world!" 并保存文件。你会发现这个改变也会立即在浏览器的http://localhost:3000 中同步渲染。现在删掉 <a> 标签并保存,"Learn React"链接也会同样被删除。

        - -

        你的 App 组件应该如下所示:

        - -
        function App() {
        -  return (
        -    <div className="App">
        -      <header className="App-header">
        -        <img src={logo} className="App-logo" alt="logo" />
        -        <p>
        -          Hello, World!
        -        </p>
        -      </header>
        -    </div>
        -  );
        -}
        - -

        Export 语句

        - -

        App.js 文件的最底部, export default App 语句使得 App 组件能被其它模块使用。

        - -

        Interrogating the index

        - -

        现在让我们打开 src/index.js, 因为这也是 App 组件被用到的地方。这个文件是我们 app 的入口点,在一开始它如下所示

        - -
        import React from 'react';
        -import ReactDOM from 'react-dom';
        -import './index.css';
        -import App from './App';
        -import * as serviceWorker from './serviceWorker';
        -
        -ReactDOM.render(<App />, document.getElementById('root'));
        -
        -// If you want your app to work offline and load faster, you can change
        -// unregister() to register() below. Note this comes with some pitfalls.
        -// Learn more about service workers: https://bit.ly/CRA-PWA
        -serviceWorker.unregister();
        - -

        就像 App.js 一样,这个文件一开始 import 了所有的 JS 模块和其它运行所需要的资源。src/index.css定义了运用于整个 app 的 global style。我们可以看到我们的 App 组件也被 imported 了,这是在 App.js 底部的语句让 import App 变得可行。

        - -

        第七行调用 React 的 ReactDOM.render() 函数,并传入两个参数:

        - -
          -
        • 我们想要渲染的组件,在这个例子中是 <App /> .
        • - -
        • 我们想要渲染组件所在的 DOM 元素,在这个例子中是带着 root 标签的元素。让我们看一下 public/index.html 的代码,可以看到这有一个 <div> 元素 在 <body> 里。
        • -
        - -

        上述所有都告诉 React 我们想把 App 组件作为 root 或者第一个组件来渲染我们的 React App。

        - -
        -

        备注:在 JSX 中,React 组件和 HTML 元素必须有关闭斜杠(/),如 <App />,如果我们写 <App> 或者 <img> 将会报错。

        -
        - -

        Service workers 能让我们的 App 离线运行,但它不在本篇文章的范围中,您可以删除第 5 行和第 9 到 12 行。

        - -

        您最终的 index.js 文件应该如下所示:

        - -
        import React from 'react';
        -import ReactDOM from 'react-dom';
        -import './index.css';
        -import App from './App';
        -
        -ReactDOM.render(<App />, document.getElementById('root'));
        - -

        Variables and props

        - -

        接下来,我们将使用一些 JavaScript 的技巧来让我们在 React 中编辑组件以及处理数据更加顺手。我们将讨论如何在 JSX 中 使用 variables,并且介绍 props,props 是我们用来往组件里传入数据的一种方法,传入之后我们可以用 variable 访问传入的变量。

        - -

        Variables in JSX

        - -

        回到 App.js, 让我们看一下第 9 行:

        - -
        <img src={logo} className="App-logo" alt="logo" />
        - -

        可以看到, <img /> 标签的 src 属性值是在大括号中的 -- {logo}. 这是 JSX 识别变量的方式。React 将会识别 {logo},知道您在我们 app 第二行引入的 logo,然后 React 会读取这个文件它并渲染。

        - -

        让我们试着设置一个我们自己的变量,在 App return 之前,添加 const subject = 'React';。您的代码现在应该如下所示:

        - -
        function App() {
        -  const subject = "React";
        -  return (
        -    <div className="App">
        -      <header className="App-header">
        -        <img src={logo} className="App-logo" alt="logo" />
        -        <p>
        -          Hello, World!
        -        </p>
        -      </header>
        -    </div>
        -  );
        -}
        - -

        把第 8 行的 "world" 替换成我们自己的变量 subject ,如下所示:

        - -
        function App() {
        -  const subject = "React";
        -  return (
        -    <div className="App">
        -      <header className="App-header">
        -        <img src={logo} className="App-logo" alt="logo" />
        -        <p>
        -          Hello, {subject}!
        -        </p>
        -      </header>
        -    </div>
        -  );
        -}
        - -

        当我们保存时,浏览器将会显示 "Hello, React!",而不是 "Hello, world!"

        - -

        变量十分方便,但是我们没有利用到 React 的特性,接下来我们将介绍 Props。

        - -

        Component props

        - -

        prop 是任何传入 React 组件的数据。Props 写在组件中,并且像 HTML 属性一样写成 prop="value"。让我们打开 index.js 并且为我们的 <App/> 添加第一个 prop。

        - -

        <App/> 组件添加一个叫 subject 并有着 Clarice 值的 prop。当完成之后,您的代码应如下所示:

        - -
        ReactDOM.render(<App subject="Clarice" />, document.getElementById('root'));
        - -

        回到 App.js,代码应该如下所示(return 中的内容省略了) - -

        function App() {
        -  const subject = "React";
        -  return (
        -    // return statement
        -  );
        -}
        - -

        改变 App 的函数签名,让它接收 props 作为一个参数。就像其它参数一样,您可以把 props 放在 console.log() 中,让其在浏览器打印出来。把它放在您的 subject 之后,以及 return 之前,您的代码应如下所示:

        - -
        function App(props) {
        -  const subject = "React";
        -  console.log(props);
        -  return (
        -    // return statement
        -  );
        -}
        - -

        保存您的文件并检查您浏览器中的 JavaScript Console,您将会发现如下所示的语句:

        - -
        Object { subject: "Clarice" }
        - -

        对象的 subject 属性与我们放入 App 函数签名的 prop 相对应,并且 Clarice 字符串与它的值相对应,在 React 中的组件 props 总是用这种方式传入 object 中。

        - -

        现在 subject 是我们的 props 之一了,让我们在 App.js 中使用它。用 props.subject 替代原本的 React 字符串,如果你想的话,也可以删除 console.log(),您的代码将如下所示: - -

        function App(props) {
        -  const subject = props.subject;
        -  return (
        -    // return statement
        -  );
        -}
        - -

        当您保存之后,app 应该会输出 "Hello, Clarice!"。如果您回到 index.js,并且修改 subject 的值并保存,您输出的字也会随之改变。

        - -

        总结

        - - -

        以上就是我们对 React 的初步认识,包括如何在本地下载它,创建一个初始 app,以及一些基本的操作。在下篇文章,我们将会开始创建我们的第一个 app -- 一个任务清单。在我们开始下篇文章之前,让我们先复习下我们现在所学的。

        - -

        在 React 中:

        - -
          -
        • 组件可以 import 它们需要的模块,并且在文件底部将自身 export,以让其它组件使用。
        • -
        • 组件是用 PascalCase 也就是帕斯卡命名法命名的。
        • -
        • 通过把变量放在大括号中,您可以读取 JSX 的变量,如{so}
        • -
        • 一些 JSX 属性与 HTML 属性不相同,这样就不会与 JavaScript 的保留字相冲突,比如说,在 HTML 中的 class 会在 JSX 中转译为 className。注意这些属性都是驼峰式命名的。
        • -
        • Props 就像属性一样写在组件里,并且传入组件。
        • -
        - -

        {{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")}}

        - -

        In this module

        - - 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 new file mode 100644 index 00000000000000..160f66ad7da52d --- /dev/null +++ b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_getting_started/index.md @@ -0,0 +1,505 @@ +--- +title: React 入门 +slug: >- + Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started +tags: + - JavaScript + - React + - 初学者 + - 学习 + - 客户端 + - 框架 +translation_of: >- + Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started +--- +{{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")}} + +本文会引导我们进入一段 React 学习之旅。我们将逐步了解有关它的背景和用例的一些细节,在自己的电脑上建起基本的 React 工具链,创建并使用一个简单的入门应用程序,以学习一些关于 React 在此过程中如何工作的知识。 + + + + + + + + + + + + +
        先决条件: +

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

        +

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

        +
        目的:要设置本地 React 开发环境,创建一个启动应用程序,并了解其工作原理
        + +## 你好 React + +如其官方口号所示,[React](https://reactjs.org/) 是一个用于构建用户界面的库。React 不是一个框架 —— 它的应用甚至不局限于 Web 开发,它可以与其他库一起使用以渲染到特定环境。例如,[React Native](https://reactnative.dev/) 可用于构建移动应用程序;[React 360](https://facebook.github.io/react-360/) 可用于构建虚拟现实应用程序…… + +为了构建 Web 应用,开发人员将 React 与 [ReactDOM 结合使用](https://reactjs.org/docs/react-dom.html)。React 和 ReactDOM 通常被与其他真正的 Web 开发框架相提并论,并用于解决相同的问题。当我们将 React 称为“框架”时,就是在进行口语化的理解。 + +React 的主要目标是最大程度地减少开发人员构建 UI 时发生的错误。它通过使用组件——描述部分用户界面的、自包含的逻辑代码段——来实现此目的。这些组件可以组合在一起以创建完整的 UI,React 将许多渲染工作进行抽象化,使您可以专注于 UI 设计 (译者注:显而易见,此设计不等于视觉稿的设计)。 + +## 用例 + +与本模块中涵盖的其他框架不同,React 不会对代码约定或文件组织实施严格的规则。这使团队可以设置最适合自己的约定,并以他们希望的任何方式采用 React。React 可以处理一个按钮,一个界面的几个部分或应用程序的整个用户界面。 + +尽管 React 可以用于[界面的小片段](https://reactjs.org/docs/add-react-to-a-website.html)中,但要和 jQuery 这样的库,甚至是像 Vue 这样的框架那样“引入”应用程序并不容易 —— 当你使用 React 构建整个应用程序时更容易上手。 + +另外,许多开发人员的经验对于 React 应用程序也是有用处的,例如使用 JSX 编写界面是需要编译过程的。在网站上添加类似于 Babel 的编译器会让网站上代码的运行速度变慢,因此开发人员通常会在构建项目的时候设置这样的工具。React 对于工具的要求可以说是很高的,但这是能够学习解决的。 + +本文将重点介绍使用 React 通过 Facebook 的 [create-react-app](https://create-react-app.dev/) 内的工具渲染应用程序中整个用户界面的用例。 + +## React 如何使用 JavaScript? + +React 中的许多模式都使用了现代 JavaScript 的功能。React 与 JavaScript 的最大区别在于 [JSX](https://reactjs.org/docs/introducing-jsx.html) 语法的使用上。JSX 是在 JavaScript 语法上的拓展,因此类似于 HTML 的代码可以和 JSX 共存。例如: + +```js +const heading =

        Mozilla Developer Network

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

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

        Mozilla Developer Network

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

        Mozilla Developer Network

        +>
        +> ``` +> +> 这看起来多少有点不适感,因为表达式前面的 [`
        `](/en-US/docs/Web/HTML/Element/header) 标记没有缩进与其对应的结束标记相同的位置。 + +浏览器是无法读取直接解析 JSX 的。我们的 header 表达式经过( [Babel](https://babeljs.io/) 或 [Parcel](https://parceljs.org/) 之类的工具)编译之后是这样的: + +```js +const header = React.createElement("header", null, + React.createElement("h1", null, "Mozilla Developer Network") +); +``` + +*可以*跳过编译步骤,并使用 [`React.createElement()`](https://reactjs.org/docs/react-api.html#createelement) 自己编写 UI。但是,这样做会失去 JSX 的声明性优势,并且代码变得更难以阅读。编译是开发过程中的一个额外步骤,但是 React 社区中的许多开发人员都认为 JSX 的可读性值得。另外,流行的工具使 JSX-to-JavaScript 编译成为其设置过程的一部分。除非您愿意,否则不必自己配置编译。 + +由于 JSX 是 HTML 和 JavaScript 的结合,因此一些开发人员认为它很直观。其他人则说它的混合特性使它变得混乱。但是,一旦熟悉了它,它将使您能够更快,更直观地构建用户界面,并使其他人一眼就能更好地理解您的代码库。 + +要阅读有关 JSX 的更多信息,请查看 React 团队的 [JSX In Depth](https://reactjs.org/docs/jsx-in-depth.html) 文章。 + +## 设置您的第一个 React 应用 + +有很多使用 React 的方法,但是我们将使用命令行界面(CLI)工具 create-react-app,如前所述,该方法通过安装一些软件包并创建一些软件包来加快开发 React 应用程序的过程。文件供您处理上述工具。 + +通过将一些 [``部分。在` +``` + +现在我们可以开始为`ToDoItem`添加实际内容了。Vue 模板目前只允许一个根元素--一个元素需要包裹模板内的所有内容(Vue 3 发布后会改变这种情况)。我们将为该根元素使用一个[`
        `](/zh-CN/docs/Web/HTML/Element/div)。 + +1. 现在在你的组件模板中添加一个空的`
        `。 +2. 在那个`
        `里面,让我们添加一个`checkbox`和一个对应的`label`。给复选框添加一个`id`,并添加一个`for`属性,将复选框映射到标签上,如下图所示。. + + ```html + + ``` + +### 在应用程序中使用 TodoItem 组件 + +这一切都很顺利,但我们还没有将组件添加到我们的应用程序中,所以没有办法测试它,看看一切是否正常。我们现在就把它添加进去吧。 + +1. 再次打开`App.vue`文件。 +2. 在` +``` + +### 使用已注册的 props + +随着组件对象中这些 props 的定义,我们可以在 template 里使用这些变量值。让我们开始向组件模版中添加 `label` prop。 + +在你的 `