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/render-props.md
+48-48Lines changed: 48 additions & 48 deletions
Original file line number
Diff line number
Diff line change
@@ -4,25 +4,25 @@ title: Render Props
4
4
permalink: docs/render-props.html
5
5
---
6
6
7
-
The term["render prop"](https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce)refers to a technique for sharing code between React components using a prop whose value is a function.
7
+
El término["render prop"](https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce)se refiere a una técnica para compartir código entre componentes en React utilizando una propiedad cuyo valor es una función.
8
8
9
-
A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.
9
+
Un componente con una `render prop` toma una función que devuelve un elemento de React y lo llama en lugar de implementar su propia lógica de representación.
10
10
11
11
```jsx
12
12
<DataProvider render={data=> (
13
13
<h1>Hello {data.target}</h1>
14
14
)}/>
15
15
```
16
16
17
-
Libraries that use render props include[React Router](https://reacttraining.com/react-router/web/api/Route/Route-render-methods)and[Downshift](https://github.com/paypal/downshift).
17
+
Algunas bibliotecas que utilizan `render props` son[React Router](https://reacttraining.com/react-router/web/api/Route/Route-render-methods)y[Downshift](https://github.com/paypal/downshift).
18
18
19
-
In this document, we’ll discuss why render props are useful, and how to write your own.
19
+
En este documento, discutiremos por qué las `render props` son útiles y cómo escribir las tuyas.
20
20
21
-
## Use Render Props for Cross-Cutting Concerns {#use-render-props-for-cross-cutting-concerns}
21
+
## Usa Render Props para preocupaciones transversales
22
22
23
-
Components are the primary unit of code reuse in React, but it's not always obvious how to share the state or behavior that one component encapsulates to other components that need that same state.
23
+
Los componentes son la unidad primaria de reutilización de código en React, pero no siempre es obvio cómo compartir el estado o el comportamiento que un componente encapsula en otros componentes que necesitan ese mismo estado.
24
24
25
-
For example, the following component tracks the mouse position in a web app:
25
+
Por ejemplo, el siguiente componente rastrea la posición del cursor en una aplicación web:
26
26
27
27
```js
28
28
classMouseTrackerextendsReact.Component {
@@ -50,14 +50,14 @@ class MouseTracker extends React.Component {
50
50
}
51
51
```
52
52
53
-
As the cursor moves around the screen, the component displays its (x, y) coordinates in a`<p>`.
53
+
A medida que el cursor se mueve alrededor de la pantalla, el componente muestra sus coordenadas (x, y) en un`<p>`.
54
54
55
-
Now the question is: How can we reuse this behavior in another component? In other words, if another component needs to know about the cursor position, can we encapsulate that behavior so that we can easily share it with that component?
55
+
Ahora la pregunta es: ¿Cómo podemos reutilizar este comportamiento en otro componente? En otras palabras, si otro componente necesita saber la posición del cursor, ¿podemos encapsular ese comportamiento para poder compartirlo fácilmente con ese componente?
56
56
57
-
Since components are the basic unit of code reuse in React, let's try refactoring the code a bit to use a`<Mouse>`component that encapsulates the behavior we need to reuse elsewhere.
57
+
Como los componentes son la unidad básica de reutilización de código en React, intentemos refactorizar el código un poco para usar un componente`<Mouse>`que encapsule el comportamiento que necesitamos reutilizar en otro lugar.
58
58
59
59
```js
60
-
//The <Mouse> component encapsulates the behavior we need...
60
+
//El componente <Mouse> encapsula el comportamiento que necesitamos...
61
61
classMouseextendsReact.Component {
62
62
constructor(props) {
63
63
super(props);
@@ -76,7 +76,7 @@ class Mouse extends React.Component {
{/* ...but how do we render something other than a <p>? */}
79
+
{/* ...pero, ¿cómo renderizamos algo más que un <p>? */}
80
80
<p>The current mouse position is ({this.state.x}, {this.state.y})</p>
81
81
</div>
82
82
);
@@ -95,11 +95,11 @@ class MouseTracker extends React.Component {
95
95
}
96
96
```
97
97
98
-
Now the `<Mouse>`component encapsulates all behavior associated with listening for `mousemove`events and storing the (x, y) position of the cursor, but it's not yet truly reusable.
98
+
Ahora, el componente `<Mouse>`encapsula todo el comportamiento asociado con la escucha de eventos `mousemove`y el almacenamiento de la posición (x, y) del cursor, pero aún no es realmente reutilizable.
99
99
100
-
For example, let's say we have a`<Cat>`component that renders the image of a cat chasing the mouse around the screen. We might use a`<Cat mouse={{ x, y }}>`prop to tell the component the coordinates of the mouse so it knows where to position the image on the screen.
100
+
Por ejemplo, digamos que tenemos un componente`<Cat>`que representa la imagen de un gato persiguiendo el cursor alrededor de la pantalla. Podríamos usar una propiedad`<Cat mouse={{ x, y }}>`para indicar al componente las coordenadas del cursor de manera que sepa dónde colocar la imagen en la pantalla.
101
101
102
-
As a first pass, you might try rendering the`<Cat>`*inside `<Mouse>`'s `render`method*, like this:
102
+
Como primer paso, puedes intentar renderizar el componente`<Cat>`*dentro del método `render`del componente `<Mouse>`*, de esta manera:
103
103
104
104
```js
105
105
classCatextendsReact.Component {
@@ -130,10 +130,10 @@ class MouseWithCat extends React.Component {
We could just swap out the <p> for a <Cat> here ... but then
134
-
we would need to create a separate <MouseWithSomethingElse>
135
-
component every time we need to use it, so <MouseWithCat>
136
-
isn't really reusable yet.
133
+
Podríamos simplemente cambiar el <p> por un <Cat> aquí ... pero luego
134
+
necesitaríamos crear un componente <MouseWithSomethingElse> separado
135
+
cada vez que necesitamos usarlo, por lo que <MouseWithCat>
136
+
no es realmente reutilizable todavía.
137
137
*/}
138
138
<Cat mouse={this.state} />
139
139
</div>
@@ -153,9 +153,9 @@ class MouseTracker extends React.Component {
153
153
}
154
154
```
155
155
156
-
This approach will work for our specific use case, but we haven't achieved the objective of truly encapsulating the behavior in a reusable way. Now, every time we want the mouse position for a different use case, we have to create a new component (i.e. essentially another `<MouseWithCat>`) that renders something specifically for that use case.
156
+
Esta propuesta funcionará para nuestro caso de uso específico, pero no hemos logrado el objetivo de realmente encapsular el comportamiento de una manera reutilizable. Ahora, cada vez que queramos saber la posición del cursor para un caso de uso diferente, debemos crear un nuevo componente (es decir, esencialmente otro `<MouseWithCat>`) que renderice algo específicamente para ese caso de uso.
157
157
158
-
Here's where the render prop comes in: Instead of hard-coding a `<Cat>`inside a `<Mouse>` component, and effectively changing its rendered output, we can provide `<Mouse>`with a function prop that it uses to dynamically determine what to render–a render prop.
158
+
Aquí es donde entran en juego las `render props`: En lugar de codificar de forma fija un componente `<Cat>`dentro del componente `<Mouse>`, y cambiar efectivamente la salida de su método render, podemos proporcionar una función por medio props a `<Mouse>`que pueda utilizar para determinar dinámicamente lo que debe renderizar -una `renderprop`.
159
159
160
160
```js
161
161
classCatextendsReact.Component {
@@ -186,8 +186,8 @@ class Mouse extends React.Component {
Instead of providing a static representation of what <Mouse> renders,
190
-
use the `render` prop to dynamically determine what to render.
189
+
En lugar de proporcionar una representación estática de lo que <Mouse> renderiza,
190
+
usa la `render prop` para determinar dinámicamente qué renderizar.
191
191
*/}
192
192
{this.props.render(this.state)}
193
193
</div>
@@ -209,17 +209,17 @@ class MouseTracker extends React.Component {
209
209
}
210
210
```
211
211
212
-
Now, instead of effectively cloning the `<Mouse>`component and hard-coding something else in its `render`method to solve for a specific use case, we provide a `render` prop that`<Mouse>`can use to dynamically determine what it renders.
212
+
Ahora, en lugar de clonar efectivamente el componente `<Mouse>`y codificar de forma fija otra cosa en su método `render`para resolver un caso de uso específico, proporcionamos una `render prop` que`<Mouse>`pueda usar para dinámicamente determinar que renderizar.
213
213
214
-
More concretely, **a render prop is a function prop that a component uses to know what to render.**
214
+
Más concretamente, **una render prop es una prop que recibe una función que un componente utiliza para saber qué renderizar.**
215
215
216
-
This technique makes the behavior that we need to share extremely portable. To get that behavior, render a`<Mouse>`with a`render` prop that tells it what to render with the current (x, y) of the cursor.
216
+
Esta técnica hace que el comportamiento que necesitamos compartir sea extremadamente portátil. Para obtener ese comportamiento, genere un`<Mouse>`con una`render prop` que le diga qué renderizar con la posición (x, y) del cursor.
217
217
218
-
One interesting thing to note about render props is that you can implement most [higher-order components](/docs/higher-order-components.html) (HOC) using a regular component with a render prop. For example, if you would prefer to have a `withMouse` HOC instead of a `<Mouse>` component, you could easily create one using a regular `<Mouse>`with a render prop:
218
+
Una cosa interesante a tener en cuenta acerca de las `render props` es que puedes implementar la mayoría de los [componentes de orden superior](/docs/higher-order-components.html) (HOC) utilizando un componente regular con una `render prop`. Por ejemplo, si prefiere tener un `withMouse` HOC en lugar de un componente `<Mouse>`, puede crear fácilmente uno usando un `<Mouse>`regular con una `render prop`:
219
219
220
220
```js
221
-
//If you really want a HOC for some reason, you can easily
222
-
//create one using a regular component with a render prop!
221
+
//Si realmente quieres un HOC por alguna razón, puedes fácilmente
222
+
//crear uno usando un componente regular con una render prop!
223
223
functionwithMouse(Component) {
224
224
returnclassextendsReact.Component {
225
225
render() {
@@ -233,21 +233,21 @@ function withMouse(Component) {
233
233
}
234
234
```
235
235
236
-
So using a render prop makes it possible to use either pattern.
236
+
Por lo tanto, usar una `render prop` hace que sea posible usar cualquier patrón.
237
237
238
-
## Using Props Other Than`render` {#using-props-other-than-render}
238
+
## Usando otras Props diferentes de`render` {#using-props-other-than-render}
239
239
240
-
It's important to remember that just because the pattern is called "render props" you don't *have to use a prop named`render`to use this pattern*. In fact, [*any* prop that is a function that a component uses to know what to render is technically a "render prop"](https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce).
240
+
Es importante recordar que solo porque el patrón se llama `render props`*no tienes que usar una prop llamada`render`para usar este patrón*. De hecho, [*cualquier* prop que es una función que un componente utiliza para saber qué renderizar es técnicamente una "render prop"](https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce).
241
241
242
-
Although the examples above use`render`, we could just as easily use the `children`prop!
242
+
Aunque los ejemplos anteriores usan`render`, ¡podríamos usar la proposición `children`con la misma facilidad!
243
243
244
244
```js
245
245
<Mouse children={mouse=> (
246
246
<p>The mouse position is {mouse.x}, {mouse.y}</p>
247
247
)}/>
248
248
```
249
249
250
-
And remember, the `children`prop doesn't actually need to be named in the list of "attributes" in your JSX element. Instead, you can put it directly *inside* the element!
250
+
Y recuerda, la propiedad `children`en realidad no necesita ser nombrada en la lista de "atributos" en su elemento JSX. En su lugar, puedes ponerlo directamente *dentro* del elemento!
251
251
252
252
```js
253
253
<Mouse>
@@ -257,27 +257,27 @@ And remember, the `children` prop doesn't actually need to be named in the list
257
257
</Mouse>
258
258
```
259
259
260
-
You'll see this technique used in the [react-motion](https://github.com/chenglou/react-motion) API.
260
+
Verás esta técnica utilizada en la API de [react-motion](https://github.com/chenglou/react-motion).
261
261
262
-
Since this technique is a little unusual, you'll probably want to explicitly state that `children`should be a function in your`propTypes`when designing an API like this.
262
+
Ya que esta técnica es un poco inusual, probablemente querrás decir explícitamente que `children`debería ser una función en tus`propTypes`cuando diseñes una API como esta.
263
263
264
264
```js
265
265
Mouse.propTypes= {
266
266
children:PropTypes.func.isRequired
267
267
};
268
268
```
269
269
270
-
## Caveats {#caveats}
270
+
## Advertencias {#caveats}
271
271
272
-
### Be careful when using Render Props with React.PureComponent {#be-careful-when-using-render-props-with-reactpurecomponent}
272
+
### Ten cuidado al usar Render Props con React.PureComponent {#be-careful-when-using-render-props-with-reactpurecomponent}
273
273
274
-
Using a render prop can negate the advantage that comes from using[`React.PureComponent`](/docs/react-api.html#reactpurecomponent)if you create the function inside a`render` method. This is because the shallow prop comparison will always return `false`for new props, and each`render`in this case will generate a new value for the render prop.
274
+
El uso de una `render prop` puede no aprovechar la ventaja del uso de[`React.PureComponent`](/docs/react-api.html#reactpurecomponent)si crea la función dentro del método`render`. Esto se debe a que la comparación de propiedades poco profundas siempre devolverá `false`para las nuevas props, y cada`render`en este caso generará un nuevo valor para la render prop.
275
275
276
-
For example, continuing with our `<Mouse>`component from above, if`Mouse`were to extend `React.PureComponent`instead of `React.Component`, our example would look like this:
276
+
Por ejemplo, continuando con nuestro componente `<Mouse>`de los ejemplos anteriores, si`Mouse`extendiera `React.PureComponent`en lugar de `React.Component`, nuestro ejemplo se vería así:
277
277
278
278
```js
279
279
classMouseextendsReact.PureComponent {
280
-
//Same implementation as above...
280
+
//Misma implementación que la anterior...
281
281
}
282
282
283
283
classMouseTrackerextendsReact.Component {
@@ -287,8 +287,8 @@ class MouseTracker extends React.Component {
287
287
<h1>Move the mouse around!</h1>
288
288
289
289
{/*
290
-
This is bad! The value of the `render` prop will
291
-
be different on each render.
290
+
¡Esto está mal! El valor de la `render prop`
291
+
será diferente en cada render.
292
292
*/}
293
293
<Mouse render={mouse=> (
294
294
<Cat mouse={mouse} />
@@ -299,14 +299,14 @@ class MouseTracker extends React.Component {
299
299
}
300
300
```
301
301
302
-
In this example, each time `<MouseTracker>` renders, it generates a new function as the value of the`<Mouse render>` prop, thus negating the effect of`<Mouse>`extending`React.PureComponent`in the first place!
302
+
En este ejemplo, cada vez que se renderiza `<MouseTracker>`, genera una nueva función como el valor de la propiedad`<Mouse render>`, negando así el efecto de`<Mouse>`extendiendo`React.PureComponent`en primer lugar!
303
303
304
-
To get around this problem, you can sometimes define the prop as an instance method, like so:
304
+
Para solucionar este problema, a veces se puede definir la prop como un método de instancia, así:
305
305
306
306
```js
307
307
classMouseTrackerextendsReact.Component {
308
-
//Defined as an instance method, `this.renderTheCat` always
309
-
//refers to *same* function when we use it in render
308
+
//Definido como un método de instancia, `this.renderTheCat` siempre
309
+
//se refiere a la *misma* función cuando la usamos en render
310
310
renderTheCat(mouse) {
311
311
return<Cat mouse={mouse} />;
312
312
}
@@ -322,4 +322,4 @@ class MouseTracker extends React.Component {
322
322
}
323
323
```
324
324
325
-
In cases where you cannot define the prop statically (e.g. because you need to close over the component's props and/or state) `<Mouse>`should extend`React.Component`instead.
325
+
En los casos en los que no puede definir la propiedad de forma estática (por ejemplo, porque necesita encerrar las props y/o el estado del componente), el `<Mouse>`debería extender`React.Component`en su lugar.
0 commit comments