【译】组件与Props

下面是react官方文档的个人翻译,如有翻译错误,请多多指出
原文地址:https://facebook.github.io/re…

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

组件能让你把UI切割成独立的,可重用的部件,并且能让你独立的思考每一个部件。

Conceptually, components are like JavaScript functions.

从概念上看,components 就像Javascript 的函数。

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

他们都允许任意的输入(叫”props”)然后返回React elements ,描述元素应该怎么显示在屏幕。

Functional and Class Components

函数以及类组件

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

定义组件最简单的方法就是写一个Javascript函数:

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

    原文作者:Blet
    原文地址: https://segmentfault.com/a/1190000008483066
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞