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/composition-vs-inheritance.md
+30-30Lines changed: 30 additions & 30 deletions
Original file line number
Diff line number
Diff line change
@@ -1,22 +1,22 @@
1
1
---
2
2
id: composition-vs-inheritance
3
-
title: Composition vs Inheritance
3
+
title: Composición vs Herencia
4
4
permalink: docs/composition-vs-inheritance.html
5
5
redirect_from:
6
6
- "docs/multiple-components.html"
7
7
prev: lifting-state-up.html
8
8
next: thinking-in-react.html
9
9
---
10
10
11
-
React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components.
11
+
React tiene un potente modelo de composición, y recomendamos usar composición en lugar de herencia para reutilizar código entre componentes.
12
12
13
-
In this section, we will consider a few problems where developers new to React often reach for inheritance, and show how we can solve them with composition.
13
+
En esta sección consideraremos algunos problemas en los que los desarrolladores nuevos en React a menudo emplean herencia, y mostraremos cómo los podemos resolver con composición.
14
14
15
-
## Containment {#containment}
15
+
## Contención {#containment}
16
16
17
-
Some components don't know their children ahead of time. This is especially common for components like`Sidebar`or`Dialog`that represent generic "boxes".
17
+
Algunos componentes no conocen sus hijos de antemano. Esto es especialmente común para componentes como`Sidebar`o`Dialog`que representan "cajas" genéricas.
18
18
19
-
We recommend that such components use the special `children` prop to pass children elements directly into their output:
19
+
Recomendamos que estos componentes usen la prop especial children para pasar elementos hijos directamente en su resultado:
20
20
21
21
```js{4}
22
22
function FancyBorder(props) {
@@ -28,28 +28,28 @@ function FancyBorder(props) {
28
28
}
29
29
```
30
30
31
-
This lets other components pass arbitrary children to them by nesting the JSX:
31
+
Esto permite que otros componentes les pasen hijos arbitrarios anidando el JSX:
32
32
33
33
```js{4-9}
34
34
function WelcomeDialog() {
35
35
return (
36
36
<FancyBorder color="blue">
37
37
<h1 className="Dialog-title">
38
-
Welcome
38
+
Bienvenidos
39
39
</h1>
40
40
<p className="Dialog-message">
41
-
Thank you for visiting our spacecraft!
41
+
¡Gracias por visitar nuestra nave espacial!
42
42
</p>
43
43
</FancyBorder>
44
44
);
45
45
}
46
46
```
47
47
48
-
**[Try it on CodePen](https://codepen.io/gaearon/pen/ozqNOV?editors=0010)**
48
+
**[Pruébalo en CodePen](https://codepen.io/gaearon/pen/ozqNOV?editors=0010)**
49
49
50
-
Anything inside the `<FancyBorder>`JSX tag gets passed into the `FancyBorder`component as a`children` prop. Since`FancyBorder`renders`{props.children}`inside a `<div>`, the passed elements appear in the final output.
50
+
Cualquier cosa dentro de la etiqueta JSX `<FancyBorder>`se pasa dentro del componente `FancyBorder`como la prop`children`. Como`FancyBorder`renderiza`{props.children}`dentro de un `<div>`, los elementos que se le han pasado aparecen en el resultado final.
51
51
52
-
While this is less common, sometimes you might need multiple "holes" in a component. In such cases you may come up with your own convention instead of using `children`:
52
+
Aunque es menos común, a veces puedes necesitar múltiples "agujeros" en un componente. En estos casos puedes inventarte tu propia convención en lugar de usar `children`:
53
53
54
54
```js{5,8,18,21}
55
55
function SplitPane(props) {
@@ -78,15 +78,15 @@ function App() {
78
78
}
79
79
```
80
80
81
-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/gwZOJp?editors=0010)
81
+
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/gwZOJp?editors=0010)
82
82
83
-
React elements like`<Contacts />`and`<Chat />`are just objects, so you can pass them as props like any other data. This approach may remind you of "slots" in other libraries but there are no limitations on what you can pass as props in React.
83
+
Los elementos como`<Contacts />`y`<Chat />`son simplemente objetos, por lo que puedes pasarlos como props como cualquier otro dato. Este enfoque puede recordarte a "huecos" (slots) en otras bibliotecas, pero no hay limitaciones en lo que puedes pasar como props en React.
84
84
85
-
## Specialization {#specialization}
85
+
## Especialización {#specialization}
86
86
87
-
Sometimes we think about components as being "special cases" of other components. For example, we might say that a `WelcomeDialog`is a special case of`Dialog`.
87
+
A veces pensamos en componentes como "casos concretos" de otros componentes. Por ejemplo, podríamos decir que un `WelcomeDialog`es un caso concreto de`Dialog`.
88
88
89
-
In React, this is also achieved by composition, where a more "specific" component renders a more "generic" one and configures it with props:
89
+
En React, esto también se consigue por composición, en la que un componente más "específico" renderiza uno más "genérico" y lo configura con props:
90
90
91
91
```js{5,8,16-18}
92
92
function Dialog(props) {
@@ -105,15 +105,15 @@ function Dialog(props) {
105
105
function WelcomeDialog() {
106
106
return (
107
107
<Dialog
108
-
title="Welcome"
109
-
message="Thank you for visiting our spacecraft!" />
108
+
title="Bienvenidos"
109
+
message="¡Gracias por visitar nuestra nave espacial!" />
110
110
);
111
111
}
112
112
```
113
113
114
-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/kkEaOZ?editors=0010)
114
+
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/kkEaOZ?editors=0010)
115
115
116
-
Composition works equally well for components defined as classes:
116
+
La composición funciona igual de bien para componentes definidos como clases:
117
117
118
118
```js{10,27-31}
119
119
function Dialog(props) {
@@ -140,12 +140,12 @@ class SignUpDialog extends React.Component {
140
140
141
141
render() {
142
142
return (
143
-
<Dialog title="Mars Exploration Program"
144
-
message="How should we refer to you?">
143
+
<Dialog title="Programa de exploración de Marte"
144
+
message="Cómo debemos llamarte?">
145
145
<input value={this.state.login}
146
146
onChange={this.handleChange} />
147
147
<button onClick={this.handleSignUp}>
148
-
Sign Me Up!
148
+
¡Apúntame!
149
149
</button>
150
150
</Dialog>
151
151
);
@@ -156,17 +156,17 @@ class SignUpDialog extends React.Component {
156
156
}
157
157
158
158
handleSignUp() {
159
-
alert(`Welcome aboard, ${this.state.login}!`);
159
+
alert(`Bienvenido abordo, ${this.state.login}!`);
160
160
}
161
161
}
162
162
```
163
163
164
-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/gwZbYa?editors=0010)
164
+
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/gwZbYa?editors=0010)
165
165
166
-
## So What About Inheritance? {#so-what-about-inheritance}
166
+
## ¿Entonces qué pasa con la herencia? {#so-what-about-inheritance}
167
167
168
-
At Facebook, we use React in thousands of components, and we haven't found any use cases where we would recommend creating component inheritance hierarchies.
168
+
En Facebook usamos React en miles de componentes, y no hemos hallado ningún caso de uso en el que recomendaríamos crear jerarquías de herencia de componentes.
169
169
170
-
Props and composition give you all the flexibility you need to customize a component's look and behavior in an explicit and safe way. Remember that components may accept arbitrary props, including primitive values, React elements, or functions.
170
+
Las props y la composición te dan toda la flexibilidad que necesitas para personalizar el aspecto y el comportamiento de un componente de forma explícita y segura. Recuerda que los componentes pueden aceptar props arbitrarias, incluyendo valores primitivos, elementos de React y funciones.
171
171
172
-
If you want to reuse non-UI functionality between components, we suggest extracting it into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it.
172
+
Si quieres reutilizar funcionalidad que no es de interfaz entre componentes, sugerimos que la extraigas en un módulo de JavaScript independiente. Los componentes pueden importarlo y usar esa función, objeto, o clase, sin extenderla.
0 commit comments