翻译练习 react-组件和props

Components and Props
组件和props

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. This page provides an introduction to the idea of components. You can find a detailed component API reference here.
组件能让把ui界面分割成独立的,可服用的并且,并且对每个模块进行独立的构思,本页面提供一个组件理念的介绍,你也可以再次找到详细的组件api参考

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
从概念上讲,组件就像js函数,它们允许任意的输入(称之为“props”)并且返回在页面上应该出现的React组件描述

Function and Class Components
函数和class组件

The simplest way to define a component is to write a JavaScript function:
一种去定义一个组件最简单的方式就是写一个js函数

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

This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions.
这个函数是一个有效的React组,因为它通过接收一个“props”(代表属性)对象参数获取数据然后返回一个React组件。我门称这类组件为函数组件因为它们本质上就是js函数

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 function components for their conciseness.
classes有一些额外的特性,我们将在下一章去讨论,在那之前 -—- 为了保持它们的简洁我们将会一直使用函数组件

Rendering a Component
渲染一个组件

Previously, we only encountered React elements that represent DOM tags:
之前,我们遇到的React元素仅仅是dom标签

const element = <div />;

However, elements can also represent user-defined components:
然而,我门可以用自定义组件去描绘react元素的

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元素是用自定义组件代替时,它通过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')
);

Try it on CodePen
在codePen上尝试一下

Let’s recap what happens in this example:
我们来看看这个例子发生了什么

  1. We call ReactDOM.render() with the <Welcome name="Sara" /> element.
    2.React calls the Welcome component with {name: 'Sara'} as the props.
    3.Our Welcome component returns a <h1>Hello, Sara</h1> element as the result.
    4.React DOM efficiently updates the DOM to match <h1>Hello, Sara</h1>.
    1.我门调用了ReactDOM。render并传入<Welcome name=“Sara” /> 作为元素
    2.react调用了Welcome 组件并把{name: ’Sara”}作为props传递
    3.我门的Welcome组件返回一个<h1>Hello, Sara</h1>元素作为结果
    4.React Dom高效的更新DOM变为<h1>Hello, Sara</h1>

Note: Always start component names with a capital letter.
React treats components starting with lowercase letters as DOM tags. For example, <div /> represents an HTML div tag, but <Welcome /> represents a component and requires Welcome to be in scope.
To learn more about the reasoning behind this convention, please read JSX In Depth.

注意:组件首字母总是要大写
React会把标签开头为小写的组件识别为DOM标签。例如<div />会识别为html的div标签,但是<Welcome />会识别称一个组件, 只能在作用域中使用

想要学习更多关于这个规范的内在理由,可以阅读深入JSX

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.
组件可以引入其他组件作为输出,-—这样可以让我们在同一个组件抽象出相同任意层次的细节-—例如一个按钮,一个表单,一个对话框,一个屏幕,在reactaap中,-—所有这些都会以普通组件的形式表现-—

For example, we can create an App component that renders Welcome many times:
例如,我门创建了一个app组件渲染了Welcome多次

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')
);

Try it on CodePen
在codePen上尝试一下

Typically, new React apps have a single App component at the very top. 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.
通常来说,新的Reactapps有一个唯一的App组件在最顶端。但是,如果你想引入React到已存在的app中美国,你可能想用一些类似button的小组件用你自己的方式去放在个个视图层级的每一处

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>
  );
}

Try it on CodePen
在codepen尝试一下

It accepts author (an object), text (a string), and date (a date) as props, and describes a comment on a social media website.
它接收一个author对象,一个text字符串,和日期作为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. This is why we have given its prop a more generic name: user rather than author.
—这个Avatar组件不需要知道在Comment里是如何染-—这是为什么我们给它的传递一个更普遍的名字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:
我们现在对Comment组件做一些微小的调整

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 the user’s name:
下一步,我们将提取一个UserInfo组件,它将在Avator组件旁渲染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>
  );
}

Try it on CodePen
在codePen中尝试一下

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,Avator),或者它的自身非常的复杂(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:
无论你是通过一个函数还是一个class声明一个组件,都一定不能修改自己的props,。
思考下这个sum函数

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组件必须像纯函数一样保护他们的props

Of course, application UIs are dynamic and change over time. In the next section, we will introduce a new concept of “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.
当然,应用程序的ui是随时动态改变的,在下一章,我门将介绍一个新的概念,state。state允许React组件响应用户行为,网络请求,或则任何其他操作去改变组件的输出内容,并且不会违反规则

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容