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
### Overriding props of an element {/*overriding-props-of-an-element*/}
27
+
### Sobreescribiendo propiedades de un elemento {/*overriding-props-of-an-element*/}
28
28
29
-
To override the props of some <CodeStepstep={1}>React element</CodeStep>, pass it to `cloneElement`with the <CodeStepstep={2}>props you want to override</CodeStep>:
29
+
Para sobreescribir las propiedades de algún <CodeStepstep={1}>React element</CodeStep>, pásalo a `cloneElement`con las <CodeStepstep={2}>propiedades que quieres sobreescribir</CodeStep>:
Here, the resulting <CodeStepstep={3}>cloned element</CodeStep> will be`<Row title="Cabbage" isHighlighted={true} />`.
41
+
Aquí, el <CodeStepstep={3}>elemento clonado</CodeStep> resultante será`<Row title="Cabbage" isHighlighted={true} />`.
42
42
43
-
**Let's walk through an example to see when it's useful.**
43
+
**Veamos un ejemplo para ver cuándo es útil.**
44
44
45
-
Imagine a `List`component that renders its [`children`](/learn/passing-props-to-a-component#passing-jsx-as-children)as a list of selectable rows with a "Next" button that changes which row is selected. The `List`component needs to render the selected `Row`differently, so it clones every `<Row>`child that it has received, and adds an extra `isHighlighted: true`or`isHighlighted: false` prop:
45
+
Imagina un componente `List`que renderiza sus [`children`](/learn/passing-props-to-a-component#passing-jsx-as-children)como una lista de filas seleccionables con un botón "Next" que cambia qué fila está seleccionada. El componente `List`necesita renderizar la `Row`seleccionada de manera diferente, por lo que clona cada hijo `<Row>`que ha recibido y agrega una propiedad extra `isHighlighted: true`o`isHighlighted: false`:
46
46
47
47
```js {6-8}
48
48
exportdefaultfunctionList({ children }) {
@@ -56,7 +56,7 @@ export default function List({ children }) {
56
56
)}
57
57
```
58
58
59
-
Let's say the original JSX received by `List`looks like this:
59
+
Digamos que el JSX original recibido por `List`se ve así:
60
60
61
61
```js {2-4}
62
62
<List>
@@ -66,7 +66,7 @@ Let's say the original JSX received by `List` looks like this:
66
66
</List>
67
67
```
68
68
69
-
By cloning its children, the `List`can pass extra information to every`Row`inside. The result looks like this:
69
+
Clonando sus hijos, `List`puede pasar información adicional a cada`Row`dentro. El resultado se ve así:
70
70
71
71
```js {4,8,12}
72
72
<List>
@@ -85,7 +85,7 @@ By cloning its children, the `List` can pass extra information to every `Row` in
85
85
</List>
86
86
```
87
87
88
-
Notice how pressing "Next" updates the state of the `List`, and highlights a different row:
88
+
Observe cómo al presionar "Next" actualiza el estado del `List`, y resalta una fila diferente:
89
89
90
90
<Sandpack>
91
91
@@ -180,21 +180,21 @@ button {
180
180
181
181
</Sandpack>
182
182
183
-
To summarize, the `List`cloned the `<Row />`elements it received and added an extra prop to them.
183
+
Para resumir, `List`clonó los elementos `<Row />`que recibió y les agregó una propiedad extra.
184
184
185
185
<Pitfall>
186
186
187
-
Cloning children makes it hard to tell how the data flows through your app. Try one of the [alternatives.](#alternatives)
187
+
Clonando los hijos hace difícil saber cómo fluye la información a través de tu aplicación. Intenta una de las [alternativas](#alternatives).
188
188
189
189
</Pitfall>
190
190
191
191
---
192
192
193
-
## Alternatives {/*alternatives*/}
193
+
## Alternativas {/*alternatives*/}
194
194
195
-
### Passing data with a render prop {/*passing-data-with-a-render-prop*/}
195
+
### Pasando datos con una render prop {/*passing-data-with-a-render-prop*/}
196
196
197
-
Instead of using `cloneElement`, consider accepting a *render prop* like`renderItem`. Here, `List`receives`renderItem`as a prop. `List`calls `renderItem`for every item and passes`isHighlighted`as an argument:
197
+
En vez de usar `cloneElement`, considera aceptar una *render prop* como`renderItem`. Aquí, `List`recibe`renderItem`como una propiedad. `List`llama a `renderItem`para cada elemento y pasa`isHighlighted`como un argumento:
The `renderItem`prop is called a "render prop" because it's a prop that specifies how to render something. For example, you can pass a `renderItem`implementation that renders a `<Row>`with the given`isHighlighted`value:
210
+
La propiedad `renderItem`se llama una "render prop" porque es una propiedad que especifica cómo renderizar algo. Por ejemplo, puedes pasar una implementación de `renderItem`que renderice un `<Row>`con el valor`isHighlighted`dado:
211
211
212
212
```js {3,7}
213
213
<List
@@ -222,7 +222,7 @@ The `renderItem` prop is called a "render prop" because it's a prop that specifi
222
222
/>
223
223
```
224
224
225
-
The end result is the same as with`cloneElement`:
225
+
El resultado final es el mismo que con`cloneElement`:
226
226
227
227
```js {4,8,12}
228
228
<List>
@@ -241,7 +241,7 @@ The end result is the same as with `cloneElement`:
241
241
</List>
242
242
```
243
243
244
-
However, you can clearly trace where the `isHighlighted` value is coming from.
244
+
Sin embargo, puedes rastrear claramente de dónde viene el valor `isHighlighted`.
245
245
246
246
<Sandpack>
247
247
@@ -337,22 +337,22 @@ button {
337
337
338
338
</Sandpack>
339
339
340
-
This pattern is preferred to`cloneElement`because it is more explicit.
340
+
Este patrón es preferido a`cloneElement`porque es más explícito.
341
341
342
342
---
343
343
344
-
### Passing data through context {/*passing-data-through-context*/}
344
+
### Pasando datos a través del contexto {/*passing-data-through-context*/}
345
345
346
-
Another alternative to`cloneElement`is to [pass data through context.](/learn/passing-data-deeply-with-context)
346
+
Otra alternativa a`cloneElement`es [pasar datos a través del contexto.](/learn/passing-data-deeply-with-context)
347
347
348
348
349
-
For example, you can call [`createContext`](/apis/react/createContext) to define a`HighlightContext`:
349
+
Por ejemplo, puedes llamar a [`createContext`](/apis/react/createContext) para definir un`HighlightContext`:
350
350
351
351
```js
352
352
exportconstHighlightContext=createContext(false);
353
353
```
354
354
355
-
Your `List`component can wrap every item it renders into a `HighlightContext` provider:
355
+
Tu componente `List`puede envolver cada elemento que renderiza en un proveedor de `HighlightContext`:
With this approach, `Row`does not need to receive an `isHighlighted`prop at all. Instead, it reads the context:
372
+
Con este enfoque, `Row`no necesita recibir una propiedad `isHighlighted`en absoluto. En su lugar, lee el contexto:
373
373
374
374
```js Row.js {2}
375
375
exportdefaultfunctionRow({ title }) {
376
376
constisHighlighted=useContext(HighlightContext);
377
377
// ...
378
378
````
379
379
380
-
This allows the calling component to not know or worry about passing `isHighlighted`to`<Row>`:
380
+
Esto permite que el componente que llama no sepa o se preocupe por pasar `isHighlighted`a`<Row>`:
381
381
382
382
```js {4}
383
383
<List
@@ -388,7 +388,7 @@ This allows the calling component to not know or worry about passing `isHighligh
388
388
/>
389
389
```
390
390
391
-
Instead, `List`and`Row`coordinate the highlighting logic through context.
391
+
En vez de eso, `List`y`Row`coordinan la lógica de resaltado a través del contexto.
392
392
393
393
<Sandpack>
394
394
@@ -498,13 +498,13 @@ button {
498
498
499
499
</Sandpack>
500
500
501
-
[Learn more about passing data through context.](/apis/react/useContext#passing-data-deeply-into-the-tree)
501
+
[Aprende más sobre pasar datos a través del contexto.](/apis/react/useContext#passing-data-deeply-into-the-tree)
502
502
503
503
---
504
504
505
-
### Extracting logic into a custom Hook {/*extracting-logic-into-a-custom-hook*/}
505
+
### Extrayendo lógica en un Hook personalizado {/*extracting-logic-into-a-custom-hook*/}
506
506
507
-
Another approach you can try is to extract the "non-visual"logic into your own Hook, and use the information returned by your Hook to decide what to render. For example, you could write a `useList`custom Hook like this:
507
+
Otro enfoque que puedes probar es extraer la lógica "no visual"en tu propio Hook, y usar la información devuelta por tu Hook para decidir qué renderizar. Por ejemplo, puedes escribir un Hook personalizado `useList`como este:
508
508
509
509
```js
510
510
import { useState } from 'react';
@@ -523,7 +523,7 @@ export default function useList(items) {
523
523
}
524
524
```
525
525
526
-
Then you could use it like this:
526
+
Entonces puedes usarlo así:
527
527
528
528
```js {2,9,13}
529
529
export default function App() {
@@ -546,7 +546,7 @@ export default function App() {
546
546
}
547
547
```
548
548
549
-
The data flow is explicit, but the state is inside the `useList`custom Hook that you can use from any component:
549
+
El flujo de datos es explícito, pero el estado está dentro del Hook personalizado `useList`que puedes usar desde cualquier componente:
550
550
551
551
<Sandpack>
552
552
@@ -639,15 +639,15 @@ button {
639
639
640
640
</Sandpack>
641
641
642
-
This approach is particularly useful if you want to reuse this logic between different components.
642
+
Este enfoque es particularmente útil si quieres reutilizar esta lógica entre diferentes componentes.
*`element`:The `element`argument must be a valid React element. For example, it could be aJSXnode like `<Something />`, the result of calling [`createElement`](/apis/react/createElement), or the result of another `cloneElement` call.
671
+
*`element`:El argumento `element`debe ser un elemento React válido. Por ejemplo, podría ser un nodoJSXcomo `<Something />`, el resultado de llamar a [`createElement`](/apis/react/createElement), o el resultado de otra llamada a `cloneElement`.
672
672
673
-
*`props`:The `props`argument must either be an object or `null`. If you pass `null`, the cloned element will retain all of the original `element.props`. Otherwise, for every prop in the `props` object, the returned element will "prefer" the value from`props`over the value from`element.props`. The rest of the props will be filled from the original`element.props`. If you pass `props.key`or`props.ref`, they will replace the original ones.
673
+
*`props`:El argumento `props`debe ser un objeto o `null`. Si pasas `null`, el elemento clonado mantendrá todos los `element.props`originales. De lo contrario, para cada propiedad en el objeto `props`, el elemento devuelto "preferirá" el valor de`props`sobre el valor de`element.props`. El resto de las propiedades se completarán a partir de los`element.props`originales. Si pasas `props.key`o`props.ref`, reemplazarán a los originales.
674
674
675
-
***optional**`...children`:Zero or more child nodes. They can be any React nodes, including React elements, strings, numbers, [portals](/apis/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and`false`), and arrays of React nodes. If you don't pass any `...children` arguments, the original `element.props.children` will be preserved.
675
+
***opcional**`...children`:Cero o más nodos hijo. Pueden ser cualquier nodo React, incluidos elementos React, cadenas, números, [portales](/apis/react-dom/createPortal), nodos vacíos (`null`, `undefined`, `true`, y`false`), y matrices de nodos React. Si no pasas ningún argumento`...children`, se conservarán los `element.props.children`originales.
676
676
677
-
#### Returns {/*returns*/}
677
+
#### Devuelve {/*returns*/}
678
678
679
-
`cloneElement` returns a React element object with a few properties:
679
+
`cloneElement`devuelve un objeto de elemento React con algunas propiedades:
680
680
681
-
* `type`: Same as `element.type`.
682
-
* `props`: The result of shallowly merging `element.props` with the overriding `props` you have passed.
683
-
* `ref`: The original `element.ref`, unless it was overridden by `props.ref`.
684
-
* `key`: The original `element.key`, unless it was overridden by `props.key`.
681
+
*`type`:Igual que`element.type`.
682
+
*`props`:El resultado de mezclar superficialmente`element.props`con los `props`que has pasado para sobrescribirlos.
683
+
*`ref`:El `element.ref` original, a menos que se haya anulado con`props.ref`.
684
+
*`key`:El `element.key` original, a menos que se haya anulado con`props.key`.
685
685
686
-
Usually, you'll return the element from your component or make it a child of another element. Although you may read the element's properties, it's best to treat every element as opaque after it's created, and only render it.
686
+
Usualmente, devolverás el elemento desde tu componente o lo harás hijo de otro elemento. Aunque puedes leer las propiedades del elemento, es mejor tratar a cada elemento como opaco después de que se crea, y solo renderizarlo.
687
687
688
-
#### Caveats {/*caveats*/}
688
+
#### Advertencias {/*advertencias*/}
689
689
690
-
* Cloning an element **does not modify the original element.**
690
+
*Clonar un elemento**no modifica el elemento original.**
691
691
692
-
* You should only **pass children as multiple arguments to `createElement` if they are all statically known,** like `cloneElement(element, null, child1, child2, child3)`. If your children are dynamic, pass the entire array as the third argument: `cloneElement(element, null, listItems)`. This ensures that React will [warn you about missing `key`s](/learn/rendering-lists#keeping-list-items-in-order-with-key) for any dynamic lists. For static lists this is not necessary because they never reorder.
692
+
*Solo debes **pasar hijos como múltiples argumentos a`createElement`si todos son conocidos estáticamente**, como`cloneElement(element, null, child1, child2, child3)`. Si tus hijos son dinámicos, pasa toda la matriz como tercer argumento:`cloneElement(element, null, listItems)`. Esto garantiza que React te [advertirá sobre las `key`s que faltan](/learn/rendering-lists#keeping-list-items-in-order-with-key) para cualquier lista dinámica. Para listas estáticas no es necesario porque nunca se reordenan.
693
693
694
-
* `cloneElement` makes it harder to trace the data flow, so **try the [alternatives](/#alternatives) instead.**
694
+
*`cloneElement`hace que sea más difícil rastrear el flujo de datos, por lo que **intente las [alternativas](/#alternatives) en su lugar.**
0 commit comments