【译】组件与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的组件屡次改变它们的输出来响应用户的操做,网络的请求或者别的都不会违背这个准则。

相关文章
相关标签/搜索