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 ---- -
JavaScript 框架是现代前端 web 开发的重要部分,为开发人员提供了构建可伸缩、交互式 web 应用程序的经过测试的工具。许多现代公司使用框架作为工具的标准部分,因此许多前端开发工作现在需要框架经验。
- -作为一个有抱负的前端开发人员,很难找出从哪里开始学习框架——有这么多不同的框架可供选择,新的问题出现,他们大多以类似的方式工作,但做一些不同的事情,还有一些具体的事情时要小心使用框架。
- -在这一系列文章中,我们旨在为您提供一个舒适的起点,帮助您开始学习框架。我们的目标不是详尽地教给你所有你需要知道的关于 React/ReactDOM,或者 Vue,或者其他一些特定的框架;框架团队自己的文档已经完成了这项工作。相反,我们想备份和首先回答更基本的问题,如:
- -在此之后,我们将提供一些教程,介绍一些主要框架的基本内容,为您提供足够的上下文和熟悉感,以便您自己开始更深入地学习。我们希望你以一种实用的方式来学习框架,不要忘记 web 平台的基本最佳实践,比如可访问性。
- - - -在尝试学习客户端框架 (HTML、CSS,特别是 JavaScript) 之前,您应该首先真正学习核心 web 语言的基础知识。
- -如果你理解了框架底层的基础 Web 平台特性,你将能编写更加健壮和专业的代码,更容易地排除问题。
- -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/.
-App
组件结构和样式,为最后即将添加的独立组件定义和交互做好准备。Note: Ember 教程最后测试于 2020 年 5 月,基于 Ember/Ember CLI version 3.18.0.
- -如果你需要确认你的代码与我们的版本区别,你可以在ember-todomvc-tutorial repository找到 Ember 应用示例代码的完整版本。想要获取当前最新的版本,查看https://nullvoxpopuli.github.io/ember-todomvc-tutorial/ (这还包含了本教程未覆盖到的一些额外的特性)。
-Note: 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。
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 应用示例代码的完整版本。想要获取当前最新的版本,查看每种 JavaScript 框架都有自己不同的方式更新 DOM,处理浏览器事件,为开发者提供愉快的使用体验,这篇文章将探索“四大”框架的主要特性,从高级角度探讨框架的工作方式以及它们之间的区别。
- -先决条件: | -熟悉核心的 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.
- -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, 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>- -
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 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.
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, 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>- -
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.
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.
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.
- -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.
- -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 /> - - ...- -
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.
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.
- -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.
- -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.
- -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"); -});- -
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")}}
- -先决条件: | ++ 熟悉核心的 HTML, + CSS 和 + JavaScript 语言。 + | +
---|---|
目标: | +了解框架主要代码的特性。 | +
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 a component can seem tricky until you have some practice, but the gist is:
- -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.
- -<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!
- - - -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.
- -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.
- - - -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:
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" />- -
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>- -
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.
- -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”.
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!
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.
- -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!
- -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- -
<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.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;- -
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.
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!
- -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")}}
- -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. + | +
本文会引导我们进入一段 React 学习之旅。我们将逐步了解有关它的背景和用例的一些细节,在自己的电脑上建起基本的 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 可用于构建虚拟现实应用程序……
- -为了构建 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 的最大区别在于 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 表达式经过( Babel 或 Parcel 之类的工具)编译之后是这样的:
- -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 的方法,但是我们将使用命令行界面(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
的文件夹, 并在此文件夹里做了如下工作:
备注:如果你的电脑上安装了 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
运行的时候会在终端上显示一些与其状态相关的信息,通常情况下无需为此担心。运行需要一点时间,在此期间你可以适度放松一下。
处理完成之后,你可以 cd
到 moz-todo-react
文件夹下,然后键入 npm start
命令并回车,先前由 create-react-app 创建的脚本会启动一个地服务 localhost:3000,并打开你的默认浏览器来访问这个服务。成功启动浏览器的话,你的浏览器上会显示如下画面:
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.org 和 Package management basics。
<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 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> - ); -}- -
在 App.js
文件的最底部, export default App
语句使得 App
组件能被其它模块使用。
现在让我们打开 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 />
.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'));- -
接下来,我们将使用一些 JavaScript 的技巧来让我们在 React 中编辑组件以及处理数据更加顺手。我们将讨论如何在 JSX 中 使用 variables,并且介绍 props,props 是我们用来往组件里传入数据的一种方法,传入之后我们可以用 variable 访问传入的变量。
- -回到 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。
- -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 中:
- -PascalCase
也就是帕斯卡命名法命名的。{so}
class
会在 JSX 中转译为 className
。注意这些属性都是驼峰式命名的。{{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")}}
- -先决条件: | +
+ + 熟悉核心 HTML,CSS + 和 JavaScript 语言,了解终端/命令行。 + ++ React 使用称为 JSX(JavaScript 和 XML)的 HTML-in-JavaScript + 语法。熟悉 HTML 和 JavaScript 可以帮助您学习 + JSX,并更好地确定应用程序中的错误是与 JavaScript 还是与 React + 的更特定领域相关。 + + |
+
---|---|
目的: | +要设置本地 React 开发环境,创建一个启动应用程序,并了解其工作原理 | +