【譯】組件與Props

下面是react官方文檔的我的翻譯,若有翻譯錯誤,請多多指出
原文地址:https://facebook.github.io/re...html

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.react

組件能讓你把UI切割成獨立的,可重用的部件,而且能讓你獨立的思考每個部件。git

Conceptually, components are like JavaScript functions.github

從概念上看,components 就像Javascript 的函數。web

They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.express

他們都容許任意的輸入(叫"props")而後返回React elements ,描述元素應該怎麼顯示在屏幕。api

Functional and Class Components

函數以及類組件數組

The simplest way to define a component is to write a JavaScript function:網絡

定義組件最簡單的方法就是寫一個Javascript函數:app

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

This function is a valid React component because it accepts a single "props" object argument with data and returns a React element.

這個函數是一個合法的React element,由於他接收一個props對象參數而且返回一個React element。

We call such components "functional" because they are literally JavaScript functions.

咱們叫這樣的組件爲函數式組件,由於他們跟Javascipt的函數同樣。

You can also use an ES6 class to define a component:

你一般可使用ES6的class來定義一個組件:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

The above two components are equivalent from React's point of view.

對於React的視圖來講,上面這兩個組件是等價的。

Classes have some additional features that we will discuss in the next sections.

咱們將會在下一章討論類組件更多的功能。

Until then, we will use functional components for their conciseness.

如今,咱們會由於函數式而使用它。

Rendering a Component

渲染組件

Previously, we only encountered React elements that represent DOM tags:
之前,咱們只鼓勵用React element來表示dom 標籤:

const element = <div />;

However, elements can also represent user-defined components:

然而,elements一樣用來表示用戶定義的組件:

const element = <Welcome name="Sara" />;

When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object "props".

當React遇到一個element表示用戶定義的組件的時候,React會把JSX裏面的屬性做啊一個對象傳遞到組件中。咱們一般叫這個對象爲props。

For example, this code renders "Hello, Sara" on the page:

例如,下面的代碼渲染了"Hello, Sara"在頁面上:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

打開試試
Let's recap what happens in this example:
讓咱們來看看這段代碼作了些什麼:

  1. We call ReactDOM.render() with the <Welcome name="Sara" /> element.

咱們調用了ReactDOM.render()而且把<Welcome name="Sara" /> 做爲第一個element傳進去了。

2.React calls the Welcome component with {name: 'Sara'} as the props.

React 調用Welcome組件,而且把 {name: 'Sara'} 做爲props傳遞進去。

3.Our Welcome component returns a <h1>Hello, Sara</h1> element as the result.

咱們的Welcome組件返回了一個a <h1>Hello, Sara</h1> 元素做爲返回值。

4.React DOM efficiently updates the DOM to match <h1>Hello, Sara</h1>.

React DOM 高效的把<h1>Hello, Sara</h1>更新到DOM裏。

Caveat:
警告:
Always start component names with a capital letter.
組件的名字最好都是大寫字母開頭的。
For example, <div /> represents a DOM tag, but <Welcome /> represents a component and requires Welcome to be in scope.
舉個例子, <div />表示一個DOM標籤,但<Welcome /> 表示一個組件而且要求是一個閉合標籤。

Composing Components

Components can refer to other components in their output.
組件能引用他們的組件做爲他們的輸出。

This lets us use the same component abstraction for any level of detail.
這會讓咱們相同的組件抽象更多的細節

A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.
在React的應用中,一個組件,一個表單,一個彈出框,一個界面都被稱爲組件。

For example, we can create an App component that renders Welcome many times:
例如,咱們建立了一個將 Welecom組件 渲染屢次的組件。

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Typically, new React apps have a single App component at the very top.

技術上來說,一個新的react 應用只有一個App組件在頂部。

However, if you integrate React into an existing app, you might start bottom-up with a small component like Button and gradually work your way to the top of the view hierarchy.

然而,若是你想把react嵌入到現有的應用中,你可能須要從一個小組件像按鈕而且逐漸按你的方式替換更高的結構。

Caveat:

Components must return a single root element. This is why we added a <div> to contain all the <Welcome /> elements.

警告:

組件必須返回一個根組件。這就是咱們爲何要用一個<div>去包住全部的<Welcome />

Extracting Components

提取組件

Don't be afraid to split components into smaller components.

不要懼怕把組件切割成更小的組件

For example, consider this Comment component:
舉個例子:思考一下 Comment 組件:

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <img className="Avatar"
          src={props.author.avatarUrl}
          alt={props.author.name}
        />
        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

打開試試

It accepts author (an object), text (a string), and date (a date) as props, and describes a comment on a social media website.

上面的組件接收做者(object), text(字符串),而且日期(date)做爲它們的props,而且做爲在社交媒體網站上的評論組件。

This component can be tricky to change because of all the nesting, and it is also hard to reuse individual parts of it. Let's extract a few components from it.

由於全部的東西都被嵌套了,因此這個組件要改變就很棘手,而且也很難重用其中的一部分。讓咱們把這個組件切割成更小的組件。

First, we will extract Avatar:
首先,咱們先切割Avatar組件:

function Avatar(props) {
  return (
    <img className="Avatar"
      src={props.user.avatarUrl}
      alt={props.user.name}
    />
  );
}

The Avatar doesn't need to know that it is being rendered inside a Comment.
這個Avatar不須要知道它被Comment組件渲染出來。

This is why we have given its prop a more generic name: user rather than author.
這就是爲何咱們給組件prop一個更通用的名字: user 比 author好。

We recommend naming props from the component's own point of view rather than the context in which it is being used.

咱們要求命名組件的props的時候,要從組件自身的視圖出發,而不是他所被使用的內容上。

We can now simplify Comment a tiny bit:

咱們如今能夠簡化評論組件:

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <Avatar user={props.author} />
        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

Next, we will extract a UserInfo component that renders an Avatar next to user's name:

咱們將切割成一個渲染Avatar組件 的UserInfo組件,而且包含user名字。

function UserInfo(props) {
  return (
    <div className="UserInfo">
      <Avatar user={props.user} />
      <div className="UserInfo-name">
        {props.user.name}
      </div>
    </div>
  );
}

This lets us simplify Comment even further:

咱們更進一步看看這個簡化了的組件:

function Comment(props) {
  return (
    <div className="Comment">
      <UserInfo user={props.author} />
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

打開試試

Extracting components might seem like grunt work at first, but having a palette of reusable components pays off in larger apps.

剛開始切割組件可能看起來像麻煩的工做,但對於一個大型的應用來講,擁有一個可重用的組件是一個回報很高的事情。

A good rule of thumb is that if a part of your UI is used several times (Button, Panel, Avatar), or is complex enough on its own (App, FeedStory, Comment), it is a good candidate to be a reusable component.

一個好的經驗法則是若是你UI中某些組件被重用了屢次(如Button, Panel, Avatar),或者對於一個自身就足夠複雜的組件(App, FeedStory, Comment)來講,將它們做爲可重用的組件是一個好的選擇。

Props are Read-Only

Props 是隻可讀取的

Whether you declare a component as a function or a class, it must never modify its own props. Consider this sum function:

不管你聲明一個函數組件或者是一個類組件,它都不能修改他們的props.思考一下下面的相加函數:

function sum(a, b) {
  return a + b;
}

Such functions are called "pure" because they do not attempt to change their inputs, and always return the same result for the same inputs.

像這樣的函數,咱們稱爲純函數,由於他們不要視圖改變他們的輸入,而且老是返回一樣的輸出經過輸入一樣的參數。

In contrast, this function is impure because it changes its own input:

與此造成鮮明對比的是,這個函數是不純的,由於他改變了自身的參數的值:

function withdraw(account, amount) {
  account.total -= amount;
}

React is pretty flexible but it has a single strict rule:

React是很是靈活的,可是它有一個嚴格的準則:

All React components must act like pure functions with respect to their props.

全部的React Components 必需要想純函數那樣去接受他們的props

Of course, application UIs are dynamic and change over time.

固然,應用的UI是動態的而且常常變化的。

In the next section, we will introduce a new concept of "state".

在下一章,咱們將會介紹一個新的該你那"state"。

State allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule.

State容許React的組件屢次改變它們的輸出來響應用戶的操做,網絡的請求或者別的都不會違背這個準則。

相關文章
相關標籤/搜索