You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
docs(cn): add Thinking in React translations (reactjs#8)
* docs(cn): add `Thinking in React` translations
* docs(cn): add translation for `mock`
* docs(cn): modify phrasing in regard to review suggestions
* docs(cn): changes regarding review feedback
* docs(cn): rephrase some words & remove control characters
* docs(cn): revert Wikipedia links to English version
* docs(cn): changes for overall smoothness
React is, in our opinion, the premier way to build big, fast Web apps with JavaScript. It has scaled very well for us at Facebook and Instagram.
11
+
我们认为,React 是用 JavaScript 构建快速响应的大型 Web 应用程序的首选方式。它在 Facebook 和 Instagram 上表现优秀。
12
12
13
-
One of the many great parts of React is how it makes you think about apps as you build them. In this document, we'll walk you through the thought process of building a searchable product data table using React.
Our JSON API returns some data that looks like this:
21
+
该 JSON API 会返回以下数据:
22
22
23
23
```
24
24
[
@@ -31,118 +31,118 @@ Our JSON API returns some data that looks like this:
31
31
];
32
32
```
33
33
34
-
## Step 1: Break The UI Into A Component Hierarchy
34
+
## 第一步:将设计好的 UI 划分为组件层级
35
35
36
-
The first thing you'll want to do is to draw boxes around every component (and subcomponent) in the mock and give them all names. If you're working with a designer, they may have already done this, so go talk to them! Their Photoshop layer names may end up being the names of your React components!
But how do you know what should be its own component? Just use the same techniques for deciding if you should create a new function or object. One such technique is the [single responsibility principle](https://en.wikipedia.org/wiki/Single_responsibility_principle), that is, a component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents.
Since you're often displaying a JSON data model to a user, you'll find that if your model was built correctly, your UI (and therefore your component structure) will map nicely. That's because UI and data models tend to adhere to the same *information architecture*, which means the work of separating your UI into components is often trivial. Just break it up into components that represent exactly one piece of your data model.
You'll see here that we have five components in our simple app. We've italicized the data each component represents.
44
+
你会看到我们的简单应用中包含五个组件。我们已经将每个组件展示的数据标注为了斜体。
45
45
46
-
1.**`FilterableProductTable` (orange):**contains the entirety of the example
47
-
2.**`SearchBar` (blue):**receives all *user input*
48
-
3.**`ProductTable` (green):**displays and filters the *data collection* based on *user input*
49
-
4.**`ProductCategoryRow` (turquoise):**displays a heading for each *category*
50
-
5.**`ProductRow` (red):**displays a row for each *product*
46
+
1.**`FilterableProductTable` (橙色):**是整个示例应用的整体
47
+
2.**`SearchBar` (蓝色):**接受所有的*用户输入*
48
+
3.**`ProductTable` (绿色):**展示*数据内容*并根据*用户输入*筛选结果
49
+
4.**`ProductCategoryRow` (天蓝色):**为每一个*产品类别*展示标题
50
+
5.**`ProductRow` (红色):**每一行展示一个*产品*
51
51
52
-
If you look at `ProductTable`, you'll see that the table header (containing the "Name" and "Price" labels) isn't its own component. This is a matter of preference, and there's an argument to be made either way. For this example, we left it as part of `ProductTable`because it is part of rendering the *data collection* which is `ProductTable`'s responsibility. However, if this header grows to be complex (i.e. if we were to add affordances for sorting), it would certainly make sense to make this its own `ProductTableHeader`component.
Now that we've identified the components in our mock, let's arrange them into a hierarchy. This is easy. Components that appear within another component in the mock should appear as a child in the hierarchy:
<pdata-height="600"data-theme-id="0"data-slug-hash="BwWzwm"data-default-tab="js"data-user="lacker"data-embed-version="2"class="codepen">See the Pen <ahref="https://codepen.io/gaearon/pen/BwWzwm">Thinking In React: Step 2</a> on <ahref="http://codepen.io">CodePen</a>.</p>
Now that you have your component hierarchy, it's time to implement your app. The easiest way is to build a version that takes your data model and renders the UI but has no interactivity. It's best to decouple these processes because building a static version requires a lot of typing and no thinking, and adding interactivity requires a lot of thinking and not a lot of typing. We'll see why.
To build a static version of your app that renders your data model, you'll want to build components that reuse other components and pass data using *props*. *props*are a way of passing data from parent to child. If you're familiar with the concept of *state*, **don't use state at all**to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app, you don't need it.
You can build top-down or bottom-up. That is, you can either start with building the components higher up in the hierarchy (i.e. starting with `FilterableProductTable`) or with the ones lower in it (`ProductRow`). In simpler examples, it's usually easier to go top-down, and on larger projects, it's easier to go bottom-up and write tests as you build.
At the end of this step, you'll have a library of reusable components that render your data model. The components will only have `render()`methods since this is a static version of your app. The component at the top of the hierarchy (`FilterableProductTable`) will take your data model as a prop. If you make a change to your underlying data model and call `ReactDOM.render()` again, the UI will be updated. It's easy to see how your UI is updated and where to make changes since there's nothing complicated going on. React's**one-way data flow** (also called *one-way binding*) keeps everything modular and fast.
Simply refer to the [React docs](/docs/) if you need help executing this step.
75
+
如果你在完成这一步骤时遇到了困难,可以参阅 [React 文档](/docs/)。
76
76
77
-
### A Brief Interlude: Props vs State
77
+
### 补充说明: 有关 props 和 state
78
78
79
-
There are two types of "model" data in React: props and state. It's important to understand the distinction between the two; skim [the official React docs](/docs/interactivity-and-dynamic-uis.html) if you aren't sure what the difference is.
To build your app correctly, you first need to think of the minimal set of mutable state that your app needs. The key here is [DRY: *Don't Repeat Yourself*](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). Figure out the absolute minimal representation of the state your application needs and compute everything else you need on-demand. For example, if you're building a TODO list, just keep an array of the TODO items around; don't keep a separate state variable for the count. Instead, when you want to render the TODO count, simply take the length of the TODO items array.
85
+
为了正确地构建应用,你首先需要找出应用所需的 state 的最小表示,并根据需要计算出其他所有数据。其中的关键正是 [DRY: *Don't Repeat Yourself*](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)。只保留应用所需的可变 state 的最小集合,其他数据均由它们计算产生。比如,你要编写一个任务清单应用,你只需要保存一个包含所有事项的数组,而无需额外保存一个单独的 state 变量(用于存储任务个数)。当你需要展示任务个数时,只需要利用该数组的 length 属性即可。
86
86
87
-
Think of all of the pieces of data in our example application. We have:
87
+
我们的示例应用拥有如下数据:
88
88
89
-
*The original list of products
90
-
*The search text the user has entered
91
-
*The value of the checkbox
92
-
*The filtered list of products
89
+
*包含所有产品的原始列表
90
+
*用户输入的搜索词
91
+
*复选框是否选中的值
92
+
*经过搜索筛选的产品列表
93
93
94
-
Let's go through each one and figure out which one is state. Simply ask three questions about each piece of data:
94
+
通过问自己以下三个问题,你可以逐个检查相应数据是否属于 state:
95
95
96
-
1.Is it passed in from a parent via props? If so, it probably isn't state.
97
-
2.Does it remain unchanged over time? If so, it probably isn't state.
98
-
3.Can you compute it based on any other state or props in your component? If so, it isn't state.
96
+
1.该数据是否是由父组件通过 props 传递而来的?如果是,那它应该不是 state。
97
+
2.该数据是否随时间的推移而保持不变?如果是,那它应该也不是 state。
98
+
3.你能否根据其他 state 或 props 计算出该数据的值?如果是,那它也不是 state。
99
99
100
-
The original list of products is passed in as props, so that's not state. The search text and the checkbox seem to be state since they change over time and can't be computed from anything. And finally, the filtered list of products isn't state because it can be computed by combining the original list of products with the search text and value of the checkbox.
<pdata-height="600"data-theme-id="0"data-slug-hash="qPrNQZ"data-default-tab="js"data-user="lacker"data-embed-version="2"class="codepen">See the Pen <ahref="https://codepen.io/gaearon/pen/qPrNQZ">Thinking In React: Step 4</a> on <ahref="http://codepen.io">CodePen</a>.</p>
OK, so we've identified what the minimal set of app state is. Next, we need to identify which component mutates, or *owns*, this state.
111
+
我们已经确定了应用所需的 state 的最小集合。接下来,我们需要确定哪个组件能够改变这些 state,或者说*拥有*这些 state。
112
112
113
-
Remember: React is all about one-way data flow down the component hierarchy. It may not be immediately clear which component should own what state. **This is often the most challenging part for newcomers to understand,** so follow these steps to figure it out:
113
+
注意:React 中的数据流是单向的,并顺着组件层级从上往下传递。哪个组件应该拥有某个 state 这件事,**对初学者来说往往是最难理解的部分**。尽管这可能在一开始不是那么清晰,但你可以尝试通过以下步骤来判断:
114
114
115
-
For each piece of state in your application:
115
+
对于应用中的每一个 state:
116
116
117
-
*Identify every component that renders something based on that state.
118
-
*Find a common owner component (a single component above all the components that need the state in the hierarchy).
119
-
*Either the common owner or another component higher up in the hierarchy should own the state.
120
-
*If you can't find a component where it makes sense to own the state, create a new component simply for holding the state and add it somewhere in the hierarchy above the common owner component.
117
+
*找到根据这个 state 进行渲染的所有组件。
118
+
*找到他们的共同所有者(common owner)组件(在组件层级上高于所有需要该 state 的组件)。
Cool, so we've decided that our state lives in `FilterableProductTable`. First, add an instance property `this.state = {filterText: '', inStockOnly: false}`to`FilterableProductTable`'s `constructor`to reflect the initial state of your application. Then, pass `filterText`and`inStockOnly`to `ProductTable`and`SearchBar` as a prop. Finally, use these props to filter the rows in `ProductTable`and set the values of the form fields in `SearchBar`.
You can start seeing how your application will behave: set `filterText`to`"ball"`and refresh your app. You'll see that the data table is updated correctly.
<pdata-height="600"data-theme-id="0"data-slug-hash="LzWZvb"data-default-tab="js,result"data-user="rohan10"data-embed-version="2"data-pen-title="Thinking In React: Step 5"class="codepen">See the Pen <ahref="https://codepen.io/gaearon/pen/LzWZvb">Thinking In React: Step 5</a> on <ahref="http://codepen.io">CodePen</a>.</p>
134
+
<pdata-height="600"data-theme-id="0"data-slug-hash="LzWZvb"data-default-tab="js,result"data-user="rohan10"data-embed-version="2"data-pen-title="Thinking In React: Step 5"class="codepen">参阅 <ahref="http://codepen.io">CodePen</a> 上的 <ahref="https://codepen.io/gaearon/pen/LzWZvb">React 哲学:第五步</a>。</p>
135
135
136
-
So far, we've built an app that renders correctly as a function of props and state flowing down the hierarchy. Now it's time to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`.
136
+
到目前为止,我们已经借助自上而下传递的 props 和 state 渲染了一个应用。现在,我们将尝试让数据反向传递:处于较低层级的表单组件更新较高层级的 `FilterableProductTable` 中的 state。
137
137
138
-
React makes this data flow explicit to make it easy to understand how your program works, but it does require a little more typing than traditional two-way data binding.
If you try to type or check the box in the current version of the example, you'll see that React ignores your input. This is intentional, as we've set the `value` prop of the `input` to always be equal to the `state`passed in from `FilterableProductTable`.
Let's think about what we want to happen. We want to make sure that whenever the user changes the form, we update the state to reflect the user input. Since components should only update their own state, `FilterableProductTable`will pass callbacks to `SearchBar` that will fire whenever the state should be updated. We can use the `onChange`event on the inputs to be notified of it. The callbacks passed by `FilterableProductTable`will call `setState()`, and the app will be updated.
142
+
让我们重新梳理一下需要实现的功能:每当用户改变表单的值,我们需要改变 state 来反映用户的当前输入。由于 state 只能由拥有它们的组件进行更改,`FilterableProductTable`必须将一个能够触发 state 改变的回调函数(callback)传递给 `SearchBar`。我们可以使用输入框的 `onChange`事件来监视用户输入的变化,并通知 `FilterableProductTable`传递给 `SearchBar` 的回调函数。然后该回调函数将调用 `setState()`,从而更新应用。
143
143
144
-
Though this sounds complex, it's really just a few lines of code. And it's really explicit how your data is flowing throughout the app.
144
+
尽管描述起来有点复杂,但实际上只是几行代码而已。你可以清楚地看到你的应用中数据是如何流动的。
145
145
146
-
## And That's It
146
+
## 这就是全部了
147
147
148
-
Hopefully, this gives you an idea of how to think about building components and applications with React. While it may be a little more typing than you're used to, remember that code is read far more than it's written, and it's extremely easy to read this modular, explicit code. As you start to build large libraries of components, you'll appreciate this explicitness and modularity, and with code reuse, your lines of code will start to shrink. :)
0 commit comments