diff --git a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/index.md b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/index.md index 9a9006e6134438..a6017dc5174113 100644 --- a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/index.md +++ b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/index.md @@ -9,128 +9,110 @@ tags: - 客户端 translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks --- -
JavaScript 框架是现代前端 web 开发的重要部分,为开发人员提供了构建可伸缩、交互式 web 应用程序的经过测试的工具。许多现代公司使用框架作为工具的标准部分,因此许多前端开发工作现在需要框架经验。
- -作为一个有抱负的前端开发人员,很难找出从哪里开始学习框架——有这么多不同的框架可供选择,新的问题出现,他们大多以类似的方式工作,但做一些不同的事情,还有一些具体的事情时要小心使用框架。
- -在这一系列文章中,我们旨在为您提供一个舒适的起点,帮助您开始学习框架。我们的目标不是详尽地教给你所有你需要知道的关于 React/ReactDOM,或者 Vue,或者其他一些特定的框架;框架团队自己的文档已经完成了这项工作。相反,我们想备份和首先回答更基本的问题,如:
- -在此之后,我们将提供一些教程,介绍一些主要框架的基本内容,为您提供足够的上下文和熟悉感,以便您自己开始更深入地学习。我们希望你以一种实用的方式来学习框架,不要忘记 web 平台的基本最佳实践,比如可访问性。
- - - -在尝试学习客户端框架 (HTML、CSS,特别是 JavaScript) 之前,您应该首先真正学习核心 web 语言的基础知识。
- -如果你理解了框架底层的基础 Web 平台特性,你将能编写更加健壮和专业的代码,更容易地排除问题。
- -备注: 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/.
-App
组件结构和样式,为最后即将添加的独立组件定义和交互做好准备。备注: Ember 教程最后测试于 2020 年 5 月,基于 Ember/Ember CLI version 3.18.0.
- -如果你需要确认你的代码与我们的版本区别,你可以在ember-todomvc-tutorial repository找到 Ember 应用示例代码的完整版本。想要获取当前最新的版本,查看https://nullvoxpopuli.github.io/ember-todomvc-tutorial/ (这还包含了本教程未覆盖到的一些额外的特性)。
-备注: Vue 教程最后测试于 2020 年 5 月,基于 Vue 2.6.11.
- -如果你需要确认你的代码与我们的版本区别,你可以在todo-vue repository找到 Vue 应用示例代码的完整版本。想要获取当前当前最新的版本,查看https://mdn.github.io/todo-vue/dist/.
-ToDoItem
组件到我们的应用中了。在此章节我们将了解如何添加一组待办项数据到我们的App.vue
组件,这组数据我们随后使用v-for
指令将它们循环并显示到ToDoItem
组件中。ToDoItem
中。下一步我们要做的是让用户能够输入他们自己的待办事项到这个应用中。 为此我们需要一个文本输入框<input>
,一个在数据提交时触发的事件,一个在数据提交时被触发来添加数据和渲染列表的方法和一个用来控制数据的模型。这就是这个章节我们将要介绍的内容。v-if
和v-else
来使既有待办项目在查看状态和文本编辑状态之间切换。我们还将添加删除待办项的功能。我们在这里发布专注于主要三大框架的系列说明文章------React/ReactDOM,Ember和Vue的一些原因如下:
- -我们想在前面说一下------我们没有因为我们认为它们是最好的或者我们赞同它们而选择这些我们正在关注的框架。我们只是认为它们在上面这些方面评价比较高。
- -值得一提的是我们也希望在我们的初版发布时能够包含更多框架的内容,但是我们最终决定先把初版内容发布出来随后在此基础上再慢慢添加更多框架内容,而不是延后更长的时间。如果你最喜欢的框架没有包含在这部分内容中而且你想帮助改善这个情况,请立即告诉我们!你可以通过Matrix或Discourse联系我们或者发送邮件到我们的邮件列表mdn-admins list。
+{{LearnSidebar}} + +JavaScript 框架是现代前端 web 开发的重要部分,为开发人员提供了构建可伸缩、交互式 web 应用程序的经过测试的工具。许多现代公司使用框架作为工具的标准部分,因此许多前端开发工作现在需要框架经验。 + +作为一个有抱负的前端开发人员,很难找出从哪里开始学习框架——有这么多不同的框架可供选择,新的问题出现,他们大多以类似的方式工作,但做一些不同的事情,还有一些具体的事情时要小心使用框架。 + +在这一系列文章中,我们旨在为您提供一个舒适的起点,帮助您开始学习框架。我们的目标不是详尽地教给你所有你需要知道的关于 React/ReactDOM,或者 Vue,或者其他一些特定的框架;框架团队自己的文档已经完成了这项工作。相反,我们想备份和首先回答更基本的问题,如: + +- 为什么要使用框架?他们为我解决了什么问题? +- 当我尝试选择一个框架时,我应该问什么问题?我甚至需要使用框架吗? +- 框架有什么特性?它们一般是如何工作的?框架对这些特性的实现有何不同? +- 它们与“普通的”JavaScript 或 HTML 有什么关系? + +在此之后,我们将提供一些教程,介绍一些主要框架的基本内容,为您提供足够的上下文和熟悉感,以便您自己开始更深入地学习。我们希望你以一种实用的方式来学习框架,不要忘记 web 平台的基本最佳实践,比如可访问性。 + +**[通过“客户端框架介绍”即刻开始](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction)** + +## 前提条件 + +在尝试学习客户端框架 (HTML、CSS,特别是 JavaScript) 之前,您应该首先真正学习核心 web 语言的基础知识。 + +如果你理解了框架底层的基础 Web 平台特性,你将能编写更加健壮和专业的代码,更容易地排除问题。 + +## 说明指导 + +- [1. 客户端框架介绍](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction) + - : 我们首先从以下话题开始研究框架,框架领域的总览,JavaScript 和框架历史的简介,为什么需要框架以及框架能带给我们什么,如何考虑选择一个框架开始学习,有什么其它的客户端框架可供选择。 +- [2. 框架的主要特性](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features) + - : 每种 JavaScript 框架都有自己不同的方式更新 DOM,处理浏览器事件,为开发者提供愉悦的使用体验,这篇文章将探索“四大”框架的主要特性,从高级角度探讨框架的工作方式以及它们之间的区别。 + +## React 教程 + +> **备注:** React 教程最后测试于 2020 年 5 月,基于 React/ReactDOM 16.13.1 和 create-react-app 3.4.1. +> +> 如果你需要确认你的代码与我们的版本区别,你可以在我们的[todo-react repository](https://github.com/mdn/todo-react)仓库找到 React 应用示例代码的完整版本。想要获取当前最新的版本,查看每种 JavaScript 框架都有自己不同的方式更新 DOM,处理浏览器事件,为开发者提供愉快的使用体验,这篇文章将探索“四大”框架的主要特性,从高级角度探讨框架的工作方式以及它们之间的区别。
+每种 JavaScript 框架都有自己不同的方式更新 DOM,处理浏览器事件,为开发者提供愉快的使用体验,这篇文章将探索“四大”框架的主要特性,从高级角度探讨框架的工作方式以及它们之间的区别。先决条件: | -熟悉核心的 HTML, CSS 和 JavaScript 语言。 | -
---|---|
目标: | -了解框架主要代码的特性。 | -
先决条件: | ++ 熟悉核心的 HTML, + CSS 和 + JavaScript 语言。 + | +
目标: | +了解框架主要代码的特性。 | +
All of the frameworks discussed in this module are powered by JavaScript, and all allow you to use domain-specific languages (DSLs) in order to build your applications. In particular, React has popularized the use of JSX for writing its components, while Ember utilizes Handlebars. Unlike HTML, these languages know how to read data variables, and this data can be used to streamline the process of writing your UI.
+All of the frameworks discussed in this module are powered by JavaScript, and all allow you to use domain-specific languages (DSLs) in order to build your applications. In particular, React has popularized the use of **JSX** for writing its components, while Ember utilizes **Handlebars**. Unlike HTML, these languages know how to read data variables, and this data can be used to streamline the process of writing your UI. -Angular apps often make heavy use of TypeScript. TypeScript is not concerned with the writing of user interfaces, but it is a domain-specific language, and has significant differences to vanilla JavaScript.
+Angular apps often make heavy use of **TypeScript**. TypeScript is not concerned with the writing of user interfaces, but it is a domain-specific language, and has significant differences to vanilla JavaScript. -DSLs can't be read by the browser directly; they must be transformed into JavaScript or HTML first. Transformation is an extra step in the development process, but framework tooling generally includes the required tools to handle this step, or can be adjusted to include this step. While it is possible to build framework apps without using these domain-specific languages, embracing them will streamline your development process and make it easier to find help from the communities around those frameworks.
+DSLs can't be read by the browser directly; they must be transformed into JavaScript or HTML first. [Transformation is an extra step in the development process](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Overview#Transformation), but framework tooling generally includes the required tools to handle this step, or can be adjusted to include this step. While it is possible to build framework apps without using these domain-specific languages, embracing them will streamline your development process and make it easier to find help from the communities around those frameworks. -JSX, which stands for JavaScript and XML, is an extension of JavaScript that brings HTML-like syntax to a JavaScript environment. It was invented by the React team for use in React applications, but can be used to develop other applications — like Vue apps, for instance.
+[JSX](https://reactjs.org/docs/introducing-jsx.html), which stands for JavaScript and XML, is an extension of JavaScript that brings HTML-like syntax to a JavaScript environment. It was invented by the React team for use in React applications, but can be used to develop other applications — like Vue apps, for instance. -The following shows a simple JSX example:
+The following shows a simple JSX example: -const subject = "World"; +```js +const subject = "World"; const header = ( - <header> - <h1>Hello, {subject}!</h1> - </header> -);+
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:
+When used with React, the JSX from the previous snippet would be compiled into this: -var subject = "World"; +```js +var subject = "World"; var header = React.createElement("header", null, React.createElement("h1", null, "Hello, ", subject, "!") -);+); +``` -
When ultimately rendered by the browser, the above snippet will produce HTML that looks like this:
+When ultimately rendered by the browser, the above snippet will produce HTML that looks like this: -<header> - <h1>Hello, World!</h1> -</header>+```html +
The Handlebars templating language is not specific to Ember applications, but it is heavily utilized in Ember apps. Handlebars code resembles HTML, but it has the option of pulling data in from elsewhere. This data can be used to influence the HTML that an application ultimately builds.
+The [Handlebars](https://handlebarsjs.com/) templating language is not specific to Ember applications, but it is heavily utilized in Ember apps. Handlebars code resembles HTML, but it has the option of pulling data in from elsewhere. This data can be used to influence the HTML that an application ultimately builds. -Like JSX, Handlebars uses curly braces to inject the value of a variable. Handlebars uses a double-pair of curly braces, instead of a single pair.
+Like JSX, Handlebars uses curly braces to inject the value of a variable. Handlebars uses a double-pair of curly braces, instead of a single pair. -Given this Handlebars template:
+Given this Handlebars template: -<header> - <h1>Hello, \{{subject}}!</h1> -</header>+```html +
And this data:
+And this data: -{ +```js +{ subject: "World" -}+} +``` -
Handlebars will build HTML like this:
+Handlebars will build HTML like this: -<header> - <h1>Hello, World!</h1> -</header>+```html +
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:
+In JavaScript, that function could be written like this: -function add(a, b) { +```js +function add(a, b) { return a + b; -}+} +``` -
This code might be trivial for someone accustomed to JavaScript, but it could still be clearer. JavaScript lets us use the +
operator to concatenate strings together, so this function would technically still work if a
and b
were strings — it just might not give you the result you'd expect. What if we wanted to only allow numbers to be passed into this function? TypeScript makes that possible:
function add(a: number, b: number) { +```js +function add(a: number, b: number) { return a + b; -}+} +``` -
The : number
written after each parameter here tells TypeScript that both a
and b
must be numbers. If we were to use this function and pass '2'
into it as an argument, TypeScript would raise an error during compilation, and we would be forced to fix our mistake. We could write our own JavaScript that raises these errors for us, but it would make our source code significantly more verbose. It probably makes more sense to let TypeScript handle such checks for us.
As mentioned in the previous chapter, most frameworks have some kind of component model. React components can be written with JSX, Ember components with Handlebars, and Angular and Vue components with a templating syntax that lightly extends HTML.
+As mentioned in the previous chapter, most frameworks have some kind of component model. React components can be written with JSX, Ember components with Handlebars, and Angular and Vue components with a templating syntax that lightly extends HTML. -Regardless of their opinions on how components should be written, each framework's components offer a way to describe the external properties they may need, the internal state that the component should manage, and the events a user can trigger on the component's markup.
+Regardless of their opinions on how components should be written, each framework's components offer a way to describe the external properties they may need, the internal state that the component should manage, and the events a user can trigger on the component's markup. -The code snippets in the rest of this section will use React as an example, and are written with JSX.
+The code snippets in the rest of this section will use React as an example, and are written with JSX. -Properties, 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) { +```js +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 +```js ++} +``` -+/> +``` - This will ultimately render the following
+This will ultimately render the following [` +``` -<figure>
element in the browser, with its structure as defined in theAuthorCredit
component, and its content as defined in the props included on theAuthorCredit
component call:State
+### State -We talked about the concept of state in the previous chapter — a robust state-handling mechanism is key to an effective framework, and each component may have data that needs its state controlled. This state will persist in some way as long as the component is in use. Like props, state can be used to affect how a component is rendered.
+We talked about the concept of **state** in the previous chapter — a robust state-handling mechanism is key to an effective framework, and each component may have data that needs its state controlled. This state will persist in some way as long as the component is in use. Like props, state can be used to affect how a component is rendered. -As an example, consider a button that counts how many times it has been clicked. This component should be responsible for tracking its own count state, and could be written like this:
+As an example, consider a button that counts how many times it has been clicked. This component should be responsible for tracking its own _count_ state, and could be written like this: -function CounterButton() { +```js +function CounterButton() { const [count] = useState(0); return ( - <button>Clicked {count} times</button> + ); -}+} +``` -+[`useState()`](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: -
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>+```html + +``` -The
+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. -useState()
call keeps track of thecount
value in a robust way across the app, without you needing to write code to do that yourself.Events
+### Events -In order to be interactive, components need ways to respond to browser events, so our applications can respond to our users. Frameworks each provide their own syntax for listening to browser events, which reference the names of the equivalent native browser events.
+In order to be interactive, components need ways to respond to browser events, so our applications can respond to our users. Frameworks each provide their own syntax for listening to browser events, which reference the names of the equivalent native browser events. -In React, listening for the
+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: -click
event requires a special property,onClick
. Let’s update ourCounterButton
code from above to allow it to count clicks:function CounterButton() { +```js +function CounterButton() { const [count, setCount] = useState(0); return ( - <button onClick={() => setCount(count + 1)}>Clicked {count} times</button> + ); -}+} +``` -In this version we are using additional
+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. -useState()
functionality to create a specialsetCount()
function, which we can invoke to update the value ofcount
. We call this function on line 4, and setcount
to whatever its current value is, plus one.Styling components
+## Styling components -Each framework offers a way to define styles for your components — or for the application as a whole. Although each framework’s approach to defining the styles of a component is slightly different, all of them give you multiple ways to do so. With the addition of some helper modules, you can style your framework apps in Sass or Less, or transpile your CSS stylesheets with PostCSS.
+Each framework offers a way to define styles for your components — or for the application as a whole. Although each framework’s approach to defining the styles of a component is slightly different, all of them give you multiple ways to do so. With the addition of some helper modules, you can style your framework apps in [Sass](https://sass-lang.com/) or [Less](http://lesscss.org/), or transpile your CSS stylesheets with [PostCSS](https://postcss.org/). -Handling dependencies
+## Handling dependencies -All major frameworks provide mechanisms for handling dependencies — using components inside other components, sometimes with multiple hierarchy levels. As with other features, the exact mechanism will differ between frameworks, but the end result is the same. Components tend to import components into other components using the standard JavaScript module syntax, or at least something similar.
+All major frameworks provide mechanisms for handling dependencies — using components inside other components, sometimes with multiple hierarchy levels. As with other features, the exact mechanism will differ between frameworks, but the end result is the same. Components tend to import components into other components using the standard [JavaScript module syntax](/en-US/docs/Web/JavaScript/Guide/Modules), or at least something similar. -Components in components
+### Components in components -One key benefit of component-based UI architecture is that components can be composed together. Just like you can write HTML tags inside each other to build a website, you can use components inside other components to build a web application. Each framework allows you to write components that utilize (and thus depend on) other components.
+One key benefit of component-based UI architecture is that components can be composed together. Just like you can write HTML tags inside each other to build a website, you can use components inside other components to build a web application. Each framework allows you to write components that utilize (and thus depend on) other components. -For example, our
+For example, our `AuthorCredit` React component might be utilized inside an `Article` component. That means that `Article` would need to import `AuthorCredit`. -AuthorCredit
React component might be utilized inside anArticle
component. That means thatArticle
would need to importAuthorCredit
.import AuthorCredit from "./components/AuthorCredit";+```js +import AuthorCredit from "./components/AuthorCredit"; +``` -Once that’s done,
+Once that’s done, `AuthorCredit` could be used inside the `Article` component like this: -AuthorCredit
could be used inside theArticle
component like this:... +```js + ... -<AuthorCredit /> ++ ... +``` -- ... Dependency injection
+### Dependency injection -Real-world applications can often involve component structures with multiple levels of nesting. An
+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. -AuthorCredit
component nested many levels deep might, for some reason, need data from the very root level of our application.Let's say that the magazine site we're building is structured like this:
+Let's say that the magazine site we're building is structured like this: -<App> - <Home> - <Article> - <AuthorCredit {/* props */} /> - </Article> - </Home> -</App>+```js ++ +``` -+ ++ ++ Our
+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. -App
component has data that ourAuthorCredit
component needs. We could rewriteHome
andArticle
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
andArticle
don’t actually make use of the author's portrait or byline, but if we want to get that information into theAuthorCredit
, we will need to changeHome
andAuthor
to accommodate it.The problem of passing data through many layers of components is called prop drilling, and it’s not ideal for large applications.
+The problem of passing data through many layers of components is called prop drilling, and it’s not ideal for large applications. -To circumvent prop drilling, frameworks provide functionality known as dependency injection, which is a way to get certain data directly to the components that need it, without passing it through intervening levels. Each framework implements dependency injection under a different name, and in a different way, but the effect is ultimately the same.
+To circumvent prop drilling, frameworks provide functionality known as dependency injection, which is a way to get certain data directly to the components that need it, without passing it through intervening levels. Each framework implements dependency injection under a different name, and in a different way, but the effect is ultimately the same. -Angular calls this process dependency injection; Vue has
+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/). -provide()
andinject()
component methods; React has a Context API; Ember shares state through services.Lifecycle
+### Lifecycle -In the context of a framework, a component’s lifecycle is a collection of phases a component goes through from the time it is rendered by the browser (often called mounting) to the time that it is removed from the DOM (often called unmounting). Each framework names these lifecycle phases differently, and not all give developers access to the same phases. All of the frameworks follow the same general model: they allow developers to perform certain actions when the component mounts, when it renders, when it unmounts, and at many phases in between these.
+In the context of a framework, a component’s **lifecycle** is a collection of phases a component goes through from the time it is rendered by the browser (often called _mounting_) to the time that it is removed from the DOM (often called _unmounting_). Each framework names these lifecycle phases differently, and not all give developers access to the same phases. All of the frameworks follow the same general model: they allow developers to perform certain actions when the component _mounts_, when it _renders_, when it _unmounts_, and at many phases in between these. -The render phase is the most crucial to understand, because it is repeated the most times as your user interacts with your application. It's run every time the browser needs to render something new, whether that new information is an addition to what's in the browser, a deletion, or an edit of what’s there.
+The _render_ phase is the most crucial to understand, because it is repeated the most times as your user interacts with your application. It's run every time the browser needs to render something new, whether that new information is an addition to what's in the browser, a deletion, or an edit of what’s there. -This diagram of a React component's lifecycle offers a general overview of the concept.
+This [diagram of a React component's lifecycle](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/) offers a general overview of the concept. -Rendering elements
+## Rendering elements -Just as with lifecycles, frameworks take different-but-similar approaches to how they render your applications. All of them track the current rendered version of your browser's DOM, and each makes slightly different decisions about how the DOM should change as components in your application re-render. Because frameworks make these decisions for you, you typically don't interact with the DOM yourself. This abstraction away from the DOM is more complex and more memory-intensive than updating the DOM yourself, but without it, frameworks could not allow you to program in the declarative way they’re known for.
+Just as with lifecycles, frameworks take different-but-similar approaches to how they render your applications. All of them track the current rendered version of your browser's DOM, and each makes slightly different decisions about how the DOM should change as components in your application re-render. Because frameworks make these decisions for you, you typically don't interact with the DOM yourself. This abstraction away from the DOM is more complex and more memory-intensive than updating the DOM yourself, but without it, frameworks could not allow you to program in the declarative way they’re known for. -The Virtual DOM is an approach whereby information about your browser's DOM is stored in JavaScript memory. Your application updates this copy of the DOM, then compares it to the "real" DOM — the DOM that is actually rendered for your users — in order to decide what to render. The application builds a "diff" to compare the differences between the updated virtual DOM and the currently rendered DOM, and uses that diff to apply updates to the real DOM. Both React and Vue utilize a virtual DOM model, but they do not apply the exact same logic when diffing or rendering.
+The **Virtual DOM** is an approach whereby information about your browser's DOM is stored in JavaScript memory. Your application updates this copy of the DOM, then compares it to the "real" DOM — the DOM that is actually rendered for your users — in order to decide what to render. The application builds a "diff" to compare the differences between the updated virtual DOM and the currently rendered DOM, and uses that diff to apply updates to the real DOM. Both React and Vue utilize a virtual DOM model, but they do not apply the exact same logic when diffing or rendering. -You can read more about the Virtual DOM in the React docs.
+You can [read more about the Virtual DOM in the React docs](https://reactjs.org/docs/faq-internals.html#what-is-the-virtual-dom). -The Incremental DOM is similar to the virtual DOM in that it builds a DOM diff to decide what to render, but different in that it doesn't create a complete copy of the DOM in JavaScript memory. It ignores the parts of the DOM that do not need to be changed. Angular is the only framework discussed so far in this module that uses an incremental DOM.
+The **Incremental DOM** is similar to the virtual DOM in that it builds a DOM diff to decide what to render, but different in that it doesn't create a complete copy of the DOM in JavaScript memory. It ignores the parts of the DOM that do not need to be changed. Angular is the only framework discussed so far in this module that uses an incremental DOM. -You can read more about the Incremental DOM on the Auth0 blog.
+You can [read more about the Incremental DOM on the Auth0 blog](https://auth0.com/blog/incremental-dom/). -The Glimmer VM is unique to Ember. It is not a virtual DOM nor an incremental DOM; it is a separate process through which Ember's templates are transpiled into a kind of "byte code" that is easier and faster to read than JavaScript.
+The **Glimmer VM** is unique to Ember. It is not a virtual DOM nor an incremental DOM; it is a separate process through which Ember's templates are transpiled into a kind of "byte code" that is easier and faster to read than JavaScript. -Routing
+## Routing -As mentioned in the previous chapter, routing is an important part of the web experience. To avoid a broken experience in sufficiently complex apps with lots of views, each of the frameworks covered in this module provides a library (or more than one library) that helps developers implement client-side routing in their applications.
+As [mentioned in the previous chapter, routing](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction#Routing) is an important part of the web experience. To avoid a broken experience in sufficiently complex apps with lots of views, each of the frameworks covered in this module provides a library (or more than one library) that helps developers implement client-side routing in their applications. -Testing
+## Testing -All applications benefit from test coverage that ensures your software continues to behave in the way that you'd expect, and web applications are no different. Each framework's ecosystem provides tooling that facilitates the writing of tests. Testing tools are not built into the frameworks themselves, but the command-line interface tools used to generate framework apps give you access to the appropriate testing tools.
+All applications benefit from test coverage that ensures your software continues to behave in the way that you'd expect, and web applications are no different. Each framework's ecosystem provides tooling that facilitates the writing of tests. Testing tools are not built into the frameworks themselves, but the command-line interface tools used to generate framework apps give you access to the appropriate testing tools. -Each framework has extensive tools in its ecosystem, with capabilities for unit and integration testing alike.
+Each framework has extensive tools in its ecosystem, with capabilities for unit and integration testing alike. -Testing Library is a suite of testing utilities that has tools for many JavaScript environments, including React, Vue, and Angular. The Ember docs cover the testing of Ember apps.
+[Testing Library](https://testing-library.com/) is a suite of testing utilities that has tools for many JavaScript environments, including React, Vue, and Angular. The Ember docs cover the [testing of Ember apps](https://guides.emberjs.com/release/testing/). -Here’s a quick test for our
+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: -CounterButton
written with the help of React Testing Library — it tests a number of things, such as the button's existence, and whether the button is displaying the correct text after being clicked 0, 1, and 2 times:import React from "react"; +```js +import React from "react"; import { render, fireEvent } from "@testing-library/react"; import "@testing-library/jest-dom/extend-expect"; import CounterButton from "./CounterButton"; -it("renders a semantic with an initial state of 0", () => { - const { getByRole } = render(<CounterButton />); +it("renders a semantic with an initial state of 0", () => { + const { getByRole } = render(- -); const btn = getByRole("button"); expect(btn).toBeInTheDocument(); expect(btn).toHaveTextContent("Clicked 0 times"); }); -it("Increments the count when clicked", () => { - const { getByRole } = render(<CounterButton />); +it("Increments the count when clicked", () => { + const { getByRole } = render( ); const btn = getByRole("button"); fireEvent.click(btn); @@ -282,73 +319,63 @@ it("Increments the count when clicked", () => { fireEvent.click(btn); expect(btn).toHaveTextContent("Clicked 2 times"); -}); Summary
- -At this point you should have more of an idea about the actual languages, features, and tools you'll be using as you create applications with frameworks. I'm sure you’re enthusiastic to get going and actually do some coding, and that's what you are going to do next! At this point you can choose which framework you'd like to start learning first:
- - - --- -备注: We only have three framework tutorial series available now, but we hope to have more available in the future.
-{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
- -In this module
- --
+}); +``` + +## Summary + +At this point you should have more of an idea about the actual languages, features, and tools you'll be using as you create applications with frameworks. I'm sure you’re enthusiastic to get going and actually do some coding, and that's what you are going to do next! At this point you can choose which framework you'd like to start learning first: + +- [React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started) +- [Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started) +- [Vue](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started) + +> **备注:** We only have three framework tutorial series available now, but we hope to have more available in the future. + +{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}} + +## In this module + +- [Introduction to client-side frameworks](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction) +- [Framework main features](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features) +- React + + - [Getting started with React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started) + - [Beginning our React todo list](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning) + - [Componentizing our React app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components) + - [React interactivity: Events and state](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state) + - [React interactivity: Editing, filtering, conditional rendering](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering) + - [Accessibility in React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility) + - [React resources](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources) + +- Ember + + - [Getting started with Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started) + - [Ember app structure and componentization](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization) + - [Ember interactivity: Events, classes and state](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state) + - [Ember Interactivity: Footer functionality, conditional rendering](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer) + - [Routing in Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing) + - [Ember resources and troubleshooting](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources) + +- Vue + + - [Getting started with Vue](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started) + - [Creating our first Vue component](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component) + - [Rendering a list of Vue components](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists) + - [Adding a new todo form: Vue events, methods, and models](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models) + - [Styling Vue components with CSS](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling) + - [Using Vue computed properties](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties) + - [Vue conditional rendering: editing existing todos](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering) + - [Focus management with Vue refs](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management) + - [Vue resources](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources) + +- Svelte + + - [Getting started with Svelte](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started) + - [Starting our Svelte Todo list app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning) + - [Dynamic behavior in Svelte: working with variables and props](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props) + - [Componentizing our Svelte app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components) + - [Advanced Svelte: Reactivity, lifecycle, accessibility](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility) + - [Working with Svelte stores](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores) + - [TypeScript support in Svelte](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript) + - [Deployment and next steps](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next) diff --git a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_components/index.md b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_components/index.md index 242967d6396ce5..35d74fa0139e7a 100644 --- a/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_components/index.md +++ b/files/zh-cn/learn/tools_and_testing/client-side_javascript_frameworks/react_components/index.md @@ -3,448 +3,484 @@ title: Componentizingapp slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components --- -- Introduction to client-side frameworks
-- Framework main features
-- React - -
-- Ember - -
-- Vue -
--
-- Getting started with Vue
-- Creating our first Vue component
-- Rendering a list of Vue components
-- Adding a new todo form: Vue events, methods, and models
-- Styling Vue components with CSS
-- Using Vue computed properties
-- Vue conditional rendering: editing existing todos
-- Focus management with Vue refs
-- Vue resources
-- Svelte -
--
-- Getting started with Svelte
-- Starting our Svelte Todo list app
-- Dynamic behavior in Svelte: working with variables and props
-- Componentizing our Svelte app
-- Advanced Svelte: Reactivity, lifecycle, accessibility
-- Working with Svelte stores
-- TypeScript support in Svelte
-- Deployment and next steps
-{{LearnSidebar}}+{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}} -{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}- -At this point, our app is a monolith. Before we can make it do things, we need to break it apart into manageable, descriptive components. React doesn’t have any hard rules for what is and isn’t a component – that’s up to you! In this article we will show you a sensible way to break our app up into components.
+At this point, our app is a monolith. Before we can make it do things, we need to break it apart into manageable, descriptive components. React doesn’t have any hard rules for what is and isn’t a component – that’s up to you! In this article we will show you a sensible way to break our app up into components.- -
-- -Prerequisites: -- -Familiarity with the core HTML, CSS, and JavaScript languages, knowledge of the terminal/command line.
-- - + +Objective: -To show a sensible way of breaking our todo list app into components. -+ +Prerequisites: ++ ++ Familiarity with the core HTML, + CSS, and + JavaScript languages, + knowledge of the + terminal/command line. +
++ +Objective: ++ To show a sensible way of breaking our todo list app into components. + +Defining our first component
+## Defining our first component -Defining a component can seem tricky until you have some practice, but the gist is:
+Defining a component can seem tricky until you have some practice, but the gist is: --
+- If it represents an obvious "chunk" of your app, it's probably a component +- If it gets reused often, it's probably a component. -- If it represents an obvious "chunk" of your app, it's probably a component
-- If it gets reused often, it's probably a component.
-That second bullet is especially valuable: making a component out of common UI elements allows you to change your code in one place and see those changes everywhere that component is used. You don't have to break everything out into components right away, either. Let's take the second bullet point as inspiration and make a component out of the most reused, most important piece of the UI: a todo list item.
+That second bullet is especially valuable: making a component out of common UI elements allows you to change your code in one place and see those changes everywhere that component is used. You don't have to break everything out into components right away, either. Let's take the second bullet point as inspiration and make a component out of the most reused, most important piece of the UI: a todo list item. -Make a
+## 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
+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! -components
directory and then, within that, a file calledTodo.js
. Make sure you're in the root of your app before you run these!mkdir src/components -touch src/components/Todo.js+```bash +mkdir src/components +touch src/components/Todo.js +``` -Our new
+Our new `Todo.js` file is currently empty! Open it up and give it its first line: -Todo.js
file is currently empty! Open it up and give it its first line:import React from "react";+```js +import React from "react"; +``` -Since we're going to make a component called
+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: -Todo
, you can start adding the code for that toTodo.js
too, as follows. In this code, we define the function and export it on the same line:export default function Todo() { +```js +export default function Todo() { return ( ); -}+} +``` -This is OK so far, but our component has to return something! Go back to
+This is OK so far, but our component has to return something! Go back to `src/App.js`, copy the first [`src/App.js
, copy the first<li>
from inside the unordered list, and paste it intoTodo.js
so that it reads like this:`](/en-US/docs/Web/HTML/Element/li) from inside the unordered list, and paste it into `Todo.js` so that it reads like this: - export default function Todo() { +```js +export default function Todo() { return ( - <li className="todo stack-small"> - <div className="c-cb"> - <input id="todo-0" type="checkbox" defaultChecked={true} /> - <label className="todo-label" htmlFor="todo-0"> ++ ); -}+ + +++ + ++
备注: Components must always return something. If at any point in the future you try to render a component that does not return anything, React will display an error in your browser.
-Our Todo
component is complete, at least for now; now we can use it. In App.js
, add the following line near the top of the file to import Todo
:
import Todo from "./components/Todo";+```js +import Todo from "./components/Todo"; +``` -
With this component imported, you can replace all of the <li>
elements in App.js
with <Todo />
component calls. Your <ul>
should read like this:
<ul +```js +
When you look back at your browser, you'll notice something unfortunate: your list now repeats the first task three times!
+When you look back at your browser, you'll notice something unfortunate: your list now repeats the first task three times! - +![Our todo list app, with todo components repeating because the label is hardcoded into the component](todo-list-repeating-todos.png) -We don't only want to eat; we have other things to — well — to do. Next we'll look at how we can make different component calls render unique content.
+We don't only want to eat; we have other things to — well — to do. Next we'll look at how we can make different component calls render unique content. -<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.
+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. -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" />+```js +
When your browser refreshes, you will see… the exact same thing as before. We gave our <Todo />
some props, but we aren't using them yet. Let's go back to Todo.js
and remedy that.
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) { +```js +export default function Todo(props) { return ( - <li className="todo stack-small"> - <div className="c-cb"> - <input id="todo-0" type="checkbox" defaultChecked={true} /> - <label className="todo-label" htmlFor="todo-0"> +
Now your browser should show three unique tasks. Another problem remains though: they're all still checked by default.
+_Now_ your browser should show three unique tasks. Another problem remains though: they're all still checked by default. - +![Our todo list, with different todo labels now they are passed into the components as props](todo-list-unique-todos.png) -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} />+```js +
As before, we must go back to Todo.js
to actually use these props. Change the defaultChecked
attribute on the <input />
so that its value is equal to the completed
prop. Once you’re done, the Todo component's <input />
element will read like this:
<input id="todo-0" type="checkbox" defaultChecked={props.completed} />+```js + +``` -
And your browser should update to show only Eat
being checked:
If you change each <Todo />
component’s completed
prop, your browser will check or uncheck the equivalent rendered checkboxes accordingly.
id
, pleaseRight 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" />+```js +
Now go back to Todo.js
and make use of the id
prop. It needs to replace the value of the id
attribute of the <input />
element, as well as the value of its label's htmlFor
attribute:
<div className="c-cb"> - <input id={props.id} type="checkbox" defaultChecked={props.completed} /> - <label className="todo-label" htmlFor={props.id}> +```js ++ + ++``` -So far, so good?
+## So far, so good? -We’re making good use of React so far, but we could do better! Our code is repetitive. The three lines that render our
+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.` component are almost identical, with only one difference: the value of each prop. - We can clean up our code with one of JavaScript's core abilities: iteration. To use iteration, we should first re-think our tasks.
+We can clean up our code with one of JavaScript's core abilities: iteration. To use iteration, we should first re-think our tasks. -Tasks as data
+## Tasks as data -Each of our tasks currently contains three pieces of information: its name, whether it has been checked, and its unique ID. This data translates nicely to an object. Since we have more than one task, an array of objects would work well in representing this data.
+Each of our tasks currently contains three pieces of information: its name, whether it has been checked, and its unique ID. This data translates nicely to an object. Since we have more than one task, an array of objects would work well in representing this data. -In
+In `src/index.js`, make a new `const` beneath the final import, but above `ReactDOM.render()`: -src/index.js
, make a newconst
beneath the final import, but aboveReactDOM.render()
:const DATA = [ +```js +const DATA = [ { id: "todo-0", name: "Eat", completed: true }, { id: "todo-1", name: "Sleep", completed: false }, { id: "todo-2", name: "Repeat", completed: false } -];+]; +``` -Next, we'll pass
+Next, we'll pass `DATA` to `DATA
to<App />
as a prop, calledtasks
. The final line ofsrc/index.js
should read like this:` as a prop, called `tasks`. The final line of `src/index.js` should read like this: - ReactDOM.render(<App tasks={DATA} />, document.getElementById("root"));+```js +ReactDOM.render(, document.getElementById("root")); +``` - This array is now available to the App component as
+This array is now available to the App component as `props.tasks`. You can `console.log()` it to check, if you’d like. -props.tasks
. You canconsole.log()
it to check, if you’d like.-+> **备注:** `ALL_CAPS` constant names have no special meaning in JavaScript; they’re a convention that tells other developers "this data will never change after being defined here”. -备注:
-ALL_CAPS
constant names have no special meaning in JavaScript; they’re a convention that tells other developers "this data will never change after being defined here”.Rendering with iteration
+## Rendering with iteration -To render our array of objects, we have to turn each one into a
+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()
.` 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
+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: -App()
, make a newconst
calledtaskList
and usemap()
to transform it. Let's start by turning ourtasks
array into something simple: thename
of each task:const taskList = props.tasks.map(task => task.name);+```js +const taskList = props.tasks.map(task => task.name); +``` -Let’s try replacing all the children of the
+Let’s try replacing all the children of the `<ul>
withtaskList
:
<ul +```js +
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!
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 />);+```js + const taskList = props.tasks.map(task =>
Look again at your app; now our tasks look more like they used to, but they’re missing the names of the tasks themselves. Remember that each task we map over has the id
, name
, and checked
properties we want to pass into our <Todo />
component. If we put that knowledge together, we get code like this:
const taskList = props.tasks.map(task => ( - <Todo id={task.id} name={task.name} completed={task.completed} /> -));+```js +const taskList = props.tasks.map(task => ( +
Now the app looks like it did before, and our code is less repetitive.
+Now the app looks like it did before, and our code is less repetitive. -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 +```js +const taskList = props.tasks.map(task => ( ++); +``` -) -);
You should always pass a unique key to anything you render with iteration. Nothing obvious will change in your browser, but if you do not use unique keys, React will log warnings to your console and your app may behave strangely!
+**You should always pass a unique key to anything you render with iteration.** Nothing obvious will change in your browser, but if you do not use unique keys, React will log warnings to your console and your app may behave strangely! -Now that we've got our most important component sorted out, we can turn the rest of our app into components. Remembering that components are either obvious pieces of UI, or reused pieces of UI, or both, we can make two more components:
+Now that we've got our most important component sorted out, we can turn the rest of our app into components. Remembering that components are either obvious pieces of UI, or reused pieces of UI, or both, we can make two more components: -<Form/>
<FilterButton/>
Since we know we need both, we can batch some of the file creation work together with a terminal command. Run this command in your terminal, taking care that you're in the root directory of your app:
+Since we know we need both, we can batch some of the file creation work together with a terminal command. Run this command in your terminal, taking care that you're in the root directory of your app: -touch src/components/Form.js src/components/FilterButton.js+```bash +touch src/components/Form.js src/components/FilterButton.js +``` -
<Form />
Open components/Form.js
and do the following:
React
at the top of the file, like we did in Todo.js
.Form()
component with the same basic structure as Todo()
, and export that component.<form>
tags and everything between them from inside App.js
, and paste them inside Form()
’s return
statement.Form
at the end of the file.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:
+The file should read like this: -import React from "react"; +```js +import React from "react"; function FilterButton(props) { return ( - <button type="button" className="btn toggle-btn" aria-pressed="true"> - <span className="visually-hidden">Show </span> - <span>all </span> - <span className="visually-hidden"> tasks</span> - </button> + ); } -export default FilterButton;+export default FilterButton; +``` -
备注: You might notice that we are making the same mistake here as we first made for the <Todo />
component, in that each button will be the same. That’s fine! We’re going to fix up this component later on, in Back to the filter buttons.
Let's make use of our new components.
+Let's make use of our new components. -Add some more import
statements to the top of App.js
, to import them.
Then, update the return
statement of App()
so that it renders our components. When you’re done, App.js
will read like this:
import React from "react"; +```js +import React from "react"; import Form from "./components/Form"; import FilterButton from "./components/FilterButton"; import Todo from "./components/Todo"; function App(props) { - const taskList = props.tasks.map(task => ( - <Todo + const taskList = props.tasks.map(task => ( +- -) ); return ( - <div className="todoapp stack-large"> - <Form /> - <div className="filters btn-group stack-exception"> - <FilterButton /> - <FilterButton /> - <FilterButton /> - </div> - <h2 id="list-heading">3 tasks remaining</h2> - <ul + + +); } -export default App;+++ + + 3 tasks remaining
+{taskList} - </ul> - </div> +
+
With this in place, we’re almost ready to tackle some interactivity in our React app!
- -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")}}
- -本文会引导我们进入一段 React 学习之旅。我们将逐步了解有关它的背景和用例的一些细节,在自己的电脑上建起基本的 React 工具链,创建并使用一个简单的入门应用程序,以学习一些关于 React 在此过程中如何工作的知识。
+本文会引导我们进入一段 React 学习之旅。我们将逐步了解有关它的背景和用例的一些细节,在自己的电脑上建起基本的 React 工具链,创建并使用一个简单的入门应用程序,以学习一些关于 React 在此过程中如何工作的知识。先决条件: | -
- 熟悉核心 HTML,CSS 和 JavaScript 语言,了解终端/命令行。 - -React 使用称为 JSX(JavaScript 和 XML)的 HTML-in-JavaScript 语法。熟悉 HTML 和 JavaScript 可以帮助您学习 JSX,并更好地确定应用程序中的错误是与 JavaScript 还是与 React 的更特定领域相关。 - |
-
---|---|
目的: | -要设置本地 React 开发环境,创建一个启动应用程序,并了解其工作原理 | -
先决条件: | +
+ + 熟悉核心 HTML,CSS + 和 JavaScript 语言,了解终端/命令行。 + ++ React 使用称为 JSX(JavaScript 和 XML)的 HTML-in-JavaScript + 语法。熟悉 HTML 和 JavaScript 可以帮助您学习 + JSX,并更好地确定应用程序中的错误是与 JavaScript 还是与 React + 的更特定领域相关。 + + |
+
目的: | +要设置本地 React 开发环境,创建一个启动应用程序,并了解其工作原理 | +
如其官方口号所示,React 是一个用于构建用户界面的库。React 不是一个框架 —— 它的应用甚至不局限于 Web 开发,它可以与其他库一起使用以渲染到特定环境。例如,React Native 可用于构建移动应用程序;React 360 可用于构建虚拟现实应用程序……
+## 你好 React -为了构建 Web 应用,开发人员将 React 与 ReactDOM 结合使用。React 和 ReactDOM 通常被与其他真正的 Web 开发框架相提并论,并用于解决相同的问题。当我们将 React 称为“框架”时,就是在进行口语化的理解。
+如其官方口号所示,[React](https://reactjs.org/) 是一个用于构建用户界面的库。React 不是一个框架 —— 它的应用甚至不局限于 Web 开发,它可以与其他库一起使用以渲染到特定环境。例如,[React Native](https://reactnative.dev/) 可用于构建移动应用程序;[React 360](https://facebook.github.io/react-360/) 可用于构建虚拟现实应用程序…… -React 的主要目标是最大程度地减少开发人员构建 UI 时发生的错误。它通过使用组件——描述部分用户界面的、自包含的逻辑代码段——来实现此目的。这些组件可以组合在一起以创建完整的 UI,React 将许多渲染工作进行抽象化,使您可以专注于 UI 设计 (译者注:显而易见,此设计不等于视觉稿的设计)。
+为了构建 Web 应用,开发人员将 React 与 [ReactDOM 结合使用](https://reactjs.org/docs/react-dom.html)。React 和 ReactDOM 通常被与其他真正的 Web 开发框架相提并论,并用于解决相同的问题。当我们将 React 称为“框架”时,就是在进行口语化的理解。 -与本模块中涵盖的其他框架不同,React 不会对代码约定或文件组织实施严格的规则。这使团队可以设置最适合自己的约定,并以他们希望的任何方式采用 React。React 可以处理一个按钮,一个界面的几个部分或应用程序的整个用户界面。
+## 用例 -尽管 React 可以用于界面的小片段中,但要和 jQuery 这样的库,甚至是像 Vue 这样的框架那样“引入”应用程序并不容易 —— 当你使用 React 构建整个应用程序时更容易上手。
+与本模块中涵盖的其他框架不同,React 不会对代码约定或文件组织实施严格的规则。这使团队可以设置最适合自己的约定,并以他们希望的任何方式采用 React。React 可以处理一个按钮,一个界面的几个部分或应用程序的整个用户界面。 -另外,许多开发人员的经验对于 React 应用程序也是有用处的,例如使用 JSX 编写界面是需要编译过程的。在网站上添加类似于 Babel 的编译器会让网站上代码的运行速度变慢,因此开发人员通常会在构建项目的时候设置这样的工具。React 对于工具的要求可以说是很高的,但这是能够学习解决的。
+尽管 React 可以用于[界面的小片段](https://reactjs.org/docs/add-react-to-a-website.html)中,但要和 jQuery 这样的库,甚至是像 Vue 这样的框架那样“引入”应用程序并不容易 —— 当你使用 React 构建整个应用程序时更容易上手。 -本文将重点介绍使用 React 通过 Facebook 的 create-react-app 内的工具渲染应用程序中整个用户界面的用例。
+另外,许多开发人员的经验对于 React 应用程序也是有用处的,例如使用 JSX 编写界面是需要编译过程的。在网站上添加类似于 Babel 的编译器会让网站上代码的运行速度变慢,因此开发人员通常会在构建项目的时候设置这样的工具。React 对于工具的要求可以说是很高的,但这是能够学习解决的。 -React 中的许多模式都使用了现代 JavaScript 的功能。React 与 JavaScript 的最大区别在于 JSX 语法的使用上。JSX 是在 JavaScript 语法上的拓展,因此类似于 HTML 的代码可以和 JSX 共存。例如:
+## React 如何使用 JavaScript? -const heading = <h1>Mozilla Developer Network</h1>;+React 中的许多模式都使用了现代 JavaScript 的功能。React 与 JavaScript 的最大区别在于 [JSX](https://reactjs.org/docs/introducing-jsx.html) 语法的使用上。JSX 是在 JavaScript 语法上的拓展,因此类似于 HTML 的代码可以和 JSX 共存。例如: -
该 heading 常量称为 JSX 表达式。React 可以使用它在我们的应用程序中渲染 <h1>
标签。
假设出于语义原因,我们想将 heading 包装 <header>
在标记中?JSX 方法允许我们将元素彼此嵌套,就像使用 HTML 一样:
const header = ( - <header> - <h1>Mozilla Developer Network</h1> - </header> -);+假设出于语义原因,我们想将 heading 包装 [`
备注: 上一个代码段中的括号并非 JSX 的一部分,它对您的应用程序没有任何影响,括号只是用来向您(和您的计算机)表明其中的多行代码属于同一个表达式 (译者注:原文表述实在有点啰嗦)。因此上面的代码等同于:
+```js +const header = ( +const header = <header> - <h1>Mozilla Developer Network</h1> -</header>+> **备注:** 上一个代码段中的括号并非 JSX 的一部分,它对您的应用程序没有任何影响,括号只是用来向您(和您的计算机)表明其中的多行代码属于同一个表达式 (译者注:原文表述实在有点啰嗦)。因此上面的代码等同于: +> +> ```js +> const header =
这看起来多少有点不适感,因为表达式前面的 <header>
标记没有缩进与其对应的结束标记相同的位置。
浏览器是无法读取直接解析 JSX 的。我们的 header 表达式经过( Babel 或 Parcel 之类的工具)编译之后是这样的:
- -const header = React.createElement("header", null, +```js +const header = React.createElement("header", null, React.createElement("h1", null, "Mozilla Developer Network") -);- -
可以跳过编译步骤,并使用 React.createElement()
自己编写 UI。但是,这样做会失去 JSX 的声明性优势,并且代码变得更难以阅读。编译是开发过程中的一个额外步骤,但是 React 社区中的许多开发人员都认为 JSX 的可读性值得。另外,流行的工具使 JSX-to-JavaScript 编译成为其设置过程的一部分。除非您愿意,否则不必自己配置编译。
由于 JSX 是 HTML 和 JavaScript 的结合,因此一些开发人员认为它很直观。其他人则说它的混合特性使它变得混乱。但是,一旦熟悉了它,它将使您能够更快,更直观地构建用户界面,并使其他人一眼就能更好地理解您的代码库。
+*可以*跳过编译步骤,并使用 [`React.createElement()`](https://reactjs.org/docs/react-api.html#createelement) 自己编写 UI。但是,这样做会失去 JSX 的声明性优势,并且代码变得更难以阅读。编译是开发过程中的一个额外步骤,但是 React 社区中的许多开发人员都认为 JSX 的可读性值得。另外,流行的工具使 JSX-to-JavaScript 编译成为其设置过程的一部分。除非您愿意,否则不必自己配置编译。 -要阅读有关 JSX 的更多信息,请查看 React 团队的 JSX In Depth 文章。
+由于 JSX 是 HTML 和 JavaScript 的结合,因此一些开发人员认为它很直观。其他人则说它的混合特性使它变得混乱。但是,一旦熟悉了它,它将使您能够更快,更直观地构建用户界面,并使其他人一眼就能更好地理解您的代码库。 -有很多使用 React 的方法,但是我们将使用命令行界面(CLI)工具 create-react-app,如前所述,该方法通过安装一些软件包并创建一些软件包来加快开发 React 应用程序的过程。文件供您处理上述工具。
+## 设置您的第一个 React 应用 -通过将一些 <script>
元素复制到 HTML 文件中,可以在没有 create-react-app 的情况下将 React 添加到网站,但是 create-react-app CLI 是 React 应用程序的常见起点。使用它可以让您花费更多的时间来构建应用,而花更少的时间进行设置。
现在我们可以开始为ToDoItem
添加实际内容了。Vue 模板目前只允许一个根元素--一个元素需要包裹模板内的所有内容(Vue 3 发布后会改变这种情况)。我们将为该根元素使用一个<div>
。
现在在你的组件模板中添加一个空的<div>
。
在那个<div>
里面,让我们添加一个checkbox
和一个对应的label
。给复选框添加一个id
,并添加一个for
属性,将复选框映射到标签上,如下图所示。.
<template> - <div> - <input type="checkbox" id="todo-item" checked="false" /> - <label for="todo-item">My Todo Item</label> - </div> -</template>-
这一切都很顺利,但我们还没有将组件添加到我们的应用程序中,所以没有办法测试它,看看一切是否正常。我们现在就把它添加进去吧。
+1. 再次打开`App.vue`文件。 +2. 在` +``` -随着组件对象中这些 props 的定义,我们可以在 template 里使用这些变量值。让我们开始向组件模版中添加 label
prop。
在你的 <template>
中,将 <label>
标签的 contents 内容修改为 \{{label}}
。