【译】组件与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
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞