You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/docs/components-and-props.md
+49-48Lines changed: 49 additions & 48 deletions
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
1
---
2
2
id: components-and-props
3
-
title: Components and Props
3
+
title: Componentes y Propiedades
4
4
permalink: docs/components-and-props.html
5
5
redirect_from:
6
6
- "docs/reusable-components.html"
@@ -15,24 +15,25 @@ redirect_from:
15
15
prev: rendering-elements.html
16
16
next: state-and-lifecycle.html
17
17
---
18
+
Los componentes permiten separar la UI en piezas independientes, reutilizables y pensar en cada pieza de forma aislada.Esta página proporciona una introducción a la idea de los componentes.
19
+
Puedes encontrar una [API detallada sobre componentes aqui](/docs/react-component.html).
18
20
19
-
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](/docs/react-component.html).
21
+
Conceptualmente, los componentes son como las funciones de JavaScript. Aceptan entradas arbitrarias (llamadas "props") y devuelven a React elementos que describen lo que debe aparecer en la pantalla.
20
22
21
-
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.
23
+
## Componentes Funcionales y de Clase
22
24
23
-
## Function and Class Components
24
-
25
-
The simplest way to define a component is to write a JavaScript function:
25
+
La forma más sencilla de definir un componente es escribir una función de JavaScript:
26
26
27
27
```js
28
28
functionWelcome(props) {
29
29
return<h1>Hello, {props.name}</h1>;
30
30
}
31
31
```
32
32
33
-
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.
33
+
Esta función es un componente de React válido porque acepta un solo argumento de objeto "props" (que proviene de propiedades) con datos y devuelve un elemento de React. Llamamos a dichos componentes "funcionales" porque literalmente son funciones JavaScript.
34
+
35
+
También puedes utilizar una [clase de ES6](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Classes) para definir un componente:
34
36
35
-
You can also use an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes) to define a component:
36
37
37
38
```js
38
39
classWelcomeextendsReact.Component {
@@ -42,27 +43,27 @@ class Welcome extends React.Component {
42
43
}
43
44
```
44
45
45
-
The above two components are equivalent from React's point of view.
46
+
Los dos componentes anteriores son equivalentes desde el punto de vista de React.
46
47
47
-
Classes have some additional features that we will discuss in the [next sections](/docs/state-and-lifecycle.html). Until then, we will use function components for their conciseness.
48
+
Las clases tienen algunas características adicionales que veremos en las [próximas secciones](/docs/state-and-lifecycle.html). Hasta entonces, usaremos componentes funcionales por su brevedad.
48
49
49
-
## Rendering a Component
50
+
## Renderizando un Componente
50
51
51
-
Previously, we only encountered React elements that represent DOM tags:
52
+
Anteriormente, sólo encontramos elementos de React que representan las etiquetas del DOM:
52
53
53
54
```js
54
55
constelement=<div />;
55
56
```
56
57
57
-
However, elements can also represent user-defined components:
58
+
Sin embargo, los elementos también pueden representar componentes definidos por el usuario:
58
59
59
60
```js
60
61
constelement=<Welcome name="Sara"/>;
61
62
```
62
63
63
-
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".
64
+
Cuando React ve representando un componente definido por el usuario, pasa atributos JSX a este componente como un solo objeto. Llamamos a este objeto "props".
64
65
65
-
For example, this code renders "Hello, Sara" on the page:
66
+
Por ejemplo, este código muestra "Hello, Sara" en la página:
1.We call`ReactDOM.render()`with the `<Welcome name="Sara" />` element.
84
-
2. React calls the `Welcome`component with `{name: 'Sara'}`as the props.
85
-
3.Our `Welcome`component returns a`<h1>Hello, Sara</h1>`element as the result.
86
-
4. React DOM efficiently updates the DOM to match`<h1>Hello, Sara</h1>`.
84
+
1.Llamamos a`ReactDOM.render()`con el elemento `<Welcome name="Sara" />`.
85
+
2. React llama al componente `Welcome`con `{name: 'Sara'}`como "props".
86
+
3.Nuestro componente `Welcome`devuelve un elemento`<h1>Hello, Sara</h1>`como resultado.
87
+
4. React DOM actualiza eficientemente el DOM para que coincida con`<h1>Hello, Sara</h1>`.
87
88
88
-
>**Note:**Always start component names with a capital letter.
89
-
>
90
-
>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.
91
-
>
92
-
>You can read more about the reasoning behind this convention [here.](/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized)
89
+
>**Nota:**Comienza siempre los nombres de componentes con una letra mayúscula.
90
+
>
91
+
>React trata los componentes que empiezan con letras minúsculas como etiquetas del DOM. Por ejemplo, `<div />`representa una etiqueta div HTML pero`<Welcome />`representa un componente y requiere que `Welcome`esté en scope.
92
+
>
93
+
>Puedes leer mas sobre el razonamiento detras de esta convención [aquí.](/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized)
93
94
94
-
## Composing Components
95
+
## Composición de Componentes
95
96
96
-
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.
97
+
Los componentes pueden referirse a otros componentes en su salida. Esto nos permite utilizar la misma abstracción de componente para cualquier nivel de detalle. Un botón, un cuadro de diálogo, un formulario, una pantalla: en aplicaciones de React, todos son expresados comunmente como componentes.
97
98
98
-
For example, we can create an`App`component that renders `Welcome`many times:
99
+
Por ejemplo, podemos crear un componente`App`que renderiza `Welcome`muchas veces:
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.
124
+
Por lo general, las aplicaciones de React nuevas tienen un único componente `App`en lo más alto. Sin embargo, si se integra React en una aplicación existente, se podría empezar de abajo hacia arriba con un pequeño componente como `Button`y poco a poco trabajar el camino a la cima de la jerarquía de la vista.
124
125
125
-
## Extracting Components
126
+
## Extracción de Componentes
126
127
127
-
Don't be afraid to split components into smaller components.
128
+
No tengas miedo de dividir los componentes en otros más pequeños.
It accepts `author` (an object), `text` (a string), and`date` (a date) as props, and describes a comment on a social media website.
158
+
Acepta `author` (un objeto), `text` (un string), y`date` (una fecha) como props, y describe un comentario en una web de redes sociales.
158
159
159
-
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.
160
+
Este componente puede ser difícil de cambiar debido a todo el anidamiento, y támbien es difícil reusar partes individuales de él. Vamos a extraer algunos componentes del mismo.
160
161
161
-
First, we will extract`Avatar`:
162
+
Primero, vamos a extraer`Avatar`:
162
163
163
164
```js{3-6}
164
165
function Avatar(props) {
@@ -171,11 +172,11 @@ function Avatar(props) {
171
172
}
172
173
```
173
174
174
-
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`.
175
+
El`Avatar`no necesita saber que está siendo renderizado dentro de un `Comment`. Esto es por lo que le dimos a su propiedad un nombre más genérico: `user`en vez de`author`.
175
176
176
-
We recommend naming props from the component's own point of view rather than the context in which it is being used.
177
+
Recomendamos nombrar las props desde el punto de vista del componente, en vez de la del contexto en el que se va a utilizar.
177
178
178
-
We can now simplify `Comment`a tiny bit:
179
+
Ahora podemos simplificar `Comment`un poquito:
179
180
180
181
```js{5}
181
182
function Comment(props) {
@@ -198,7 +199,7 @@ function Comment(props) {
198
199
}
199
200
```
200
201
201
-
Next, we will extract a `UserInfo`component that renders an `Avatar`next to the user's name:
202
+
A continuacion, vamos a extraer un componente `UserInfo`que renderiza un `Avatar`al lado del nombre del usuario:
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.
237
+
Extraer componentes puede parecer un trabajo pesado al principio, pero tener una paleta de componentes reutilizables vale la pena en aplicaciones más grandes. Una buena regla en general es que si una parte de su UI se usa varias veces (`Button`, `Panel`, `Avatar`), o es lo suficientemente compleja por si misma (`App`, `FeedStory`, `Comment`), es buen candidato para ser un componente reutilizable.
237
238
238
-
## Props are Read-Only
239
+
## Las props son de solo lectura
239
240
240
-
Whether you declare a component [as a function or a class](#function-and-class-components), it must never modify its own props. Consider this `sum`function:
241
+
Ya sea que declares un componente [como una función o como una clase](#function-and-class-components), este nunca debe modificar sus props. Considera esta función `sum` :
241
242
242
243
```js
243
244
functionsum(a, b) {
244
245
return a + b;
245
246
}
246
247
```
247
248
248
-
Such functions are called["pure"](https://en.wikipedia.org/wiki/Pure_function)because they do not attempt to change their inputs, and always return the same result for the same inputs.
249
+
Tales funciones son llamadas["puras"](https://en.wikipedia.org/wiki/Pure_function)por que no tratan de cambiar sus entradas, y siempre devuelven el mismo resultado para las mismas entradas.
249
250
250
-
In contrast, this function is impure because it changes its own input:
251
+
En contraste, esta función es impura por que cambia su propia entrada:
251
252
252
253
```js
253
254
functionwithdraw(account, amount) {
254
255
account.total-= amount;
255
256
}
256
257
```
257
258
258
-
React is pretty flexible but it has a single strict rule:
259
+
React es bastante flexible pero tiene una sola regla estricta:
259
260
260
-
**All React components must act like pure functions with respect to their props.**
261
+
**Todos los componentes de React deben actuar como funciones puras con respecto a sus props.**
261
262
262
-
Of course, application UIs are dynamic and change over time. In the [next section](/docs/state-and-lifecycle.html), 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.
263
+
Por supuesto, las UI de las aplicaciones son dinámicas y cambian con el tiempo. En la [siguiente sección](/docs/state-and-lifecycle.html), introduciremos un nuevo concepto de "estado". El estado le permite a los componentes de React cambiar su salida a lo largo del tiempo en respuesta a acciones del usuario, respuestas de red y cualquier otra cosa, sin violar esta regla.
0 commit comments