Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

translate composition-vs-inheritance to spanish #150

Merged
merged 3 commits into from
Feb 16, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
60 changes: 30 additions & 30 deletions content/docs/composition-vs-inheritance.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
---
id: composition-vs-inheritance
title: Composition vs Inheritance
title: Composición vs Herencia
permalink: docs/composition-vs-inheritance.html
redirect_from:
- "docs/multiple-components.html"
prev: lifting-state-up.html
next: thinking-in-react.html
---

React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components.
React tiene un potente modelo de composición, y recomendamos usar composición en lugar de herencia para reutilizar código entre componentes.

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.
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.

## Containment {#containment}
## Contención {#containment}

Some components don't know their children ahead of time. This is especially common for components like `Sidebar` or `Dialog` that represent generic "boxes".
Algunos componentes no conocen sus hijos de antemano. Esto es especialmente común para componentes como `Sidebar` o `Dialog` que representan "cajas" genéricas.

We recommend that such components use the special `children` prop to pass children elements directly into their output:
Recomendamos que estos componentes usen la prop especial children para pasar elementos hijos directamente en su resultado:

```js{4}
function FancyBorder(props) {
Expand All @@ -28,28 +28,28 @@ function FancyBorder(props) {
}
```

This lets other components pass arbitrary children to them by nesting the JSX:
Esto permite que otros componentes les pasen hijos arbitrarios anidando el JSX:

```js{4-9}
function WelcomeDialog() {
return (
<FancyBorder color="blue">
<h1 className="Dialog-title">
Welcome
Bienvenidos
</h1>
<p className="Dialog-message">
Thank you for visiting our spacecraft!
¡Gracias por visitar nuestra nave espacial!
</p>
</FancyBorder>
);
}
```

**[Try it on CodePen](https://codepen.io/gaearon/pen/ozqNOV?editors=0010)**
**[Pruébalo en CodePen](https://codepen.io/gaearon/pen/ozqNOV?editors=0010)**

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.
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.

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`:
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`:

```js{5,8,18,21}
function SplitPane(props) {
Expand Down Expand Up @@ -78,15 +78,15 @@ function App() {
}
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/gwZOJp?editors=0010)
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/gwZOJp?editors=0010)

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.
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.

## Specialization {#specialization}
## Especialización {#specialization}

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`.
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`.

In React, this is also achieved by composition, where a more "specific" component renders a more "generic" one and configures it with props:
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:

```js{5,8,16-18}
function Dialog(props) {
Expand All @@ -105,15 +105,15 @@ function Dialog(props) {
function WelcomeDialog() {
return (
<Dialog
title="Welcome"
message="Thank you for visiting our spacecraft!" />
title="Bienvenidos"
message="¡Gracias por visitar nuestra nave espacial!" />
);
}
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/kkEaOZ?editors=0010)
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/kkEaOZ?editors=0010)

Composition works equally well for components defined as classes:
La composición funciona igual de bien para componentes definidos como clases:

```js{10,27-31}
function Dialog(props) {
Expand All @@ -140,12 +140,12 @@ class SignUpDialog extends React.Component {

render() {
return (
<Dialog title="Mars Exploration Program"
message="How should we refer to you?">
<Dialog title="Programa de exploración de Marte"
message="Cómo debemos llamarte?">
<input value={this.state.login}
onChange={this.handleChange} />
<button onClick={this.handleSignUp}>
Sign Me Up!
¡Apúntame!
</button>
</Dialog>
);
Expand All @@ -156,17 +156,17 @@ class SignUpDialog extends React.Component {
}

handleSignUp() {
alert(`Welcome aboard, ${this.state.login}!`);
alert(`Bienvenido abordo, ${this.state.login}!`);
}
}
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/gwZbYa?editors=0010)
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/gwZbYa?editors=0010)

## So What About Inheritance? {#so-what-about-inheritance}
## ¿Entonces qué pasa con la herencia? {#so-what-about-inheritance}

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.
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.

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.
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.

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.
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.