Skip to content

Commit 3020065

Browse files
committed
Translate cloneElement
1 parent a9bc77a commit 3020065

File tree

1 file changed

+51
-51
lines changed

1 file changed

+51
-51
lines changed

beta/src/content/apis/react/cloneElement.md

Lines changed: 51 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@ title: cloneElement
44

55
<Pitfall>
66

7-
Using `cloneElement` is uncommon and can lead to fragile code. [See common alternatives.](#alternatives)
7+
El uso de `cloneElement` no es común y puede conducir a un código frágil. [Mira alternativas comunes.](#alternatives)
88

99
</Pitfall>
1010

1111
<Intro>
1212

13-
`cloneElement` lets you create a new React element using another element as a starting point.
13+
`cloneElement` te permite crear un nuevo elemento de React usando otro elemento como punto de partida.
1414

1515
```js
1616
const clonedElement = cloneElement(element, props, ...children)
@@ -22,11 +22,11 @@ const clonedElement = cloneElement(element, props, ...children)
2222

2323
---
2424

25-
## Usage {/*usage*/}
25+
## Uso {/*usage*/}
2626

27-
### Overriding props of an element {/*overriding-props-of-an-element*/}
27+
### Sobreescribiendo propiedades de un elemento {/*overriding-props-of-an-element*/}
2828

29-
To override the props of some <CodeStep step={1}>React element</CodeStep>, pass it to `cloneElement` with the <CodeStep step={2}>props you want to override</CodeStep>:
29+
Para sobreescribir las propiedades de algún <CodeStep step={1}>React element</CodeStep>, pásalo a `cloneElement` con las <CodeStep step={2}>propiedades que quieres sobreescribir</CodeStep>:
3030

3131
```js [[1, 5, "<Row title=\\"Cabbage\\" />"], [2, 6, "{ isHighlighted: true }"], [3, 4, "clonedElement"]]
3232
import { cloneElement } from 'react';
@@ -38,11 +38,11 @@ const clonedElement = cloneElement(
3838
);
3939
```
4040

41-
Here, the resulting <CodeStep step={3}>cloned element</CodeStep> will be `<Row title="Cabbage" isHighlighted={true} />`.
41+
Aquí, el <CodeStep step={3}>elemento clonado</CodeStep> resultante será `<Row title="Cabbage" isHighlighted={true} />`.
4242

43-
**Let's walk through an example to see when it's useful.**
43+
**Veamos un ejemplo para ver cuándo es útil.**
4444

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

4747
```js {6-8}
4848
export default function List({ children }) {
@@ -56,7 +56,7 @@ export default function List({ children }) {
5656
)}
5757
```
5858
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í:
6060
6161
```js {2-4}
6262
<List>
@@ -66,7 +66,7 @@ Let's say the original JSX received by `List` looks like this:
6666
</List>
6767
```
6868
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í:
7070
7171
```js {4,8,12}
7272
<List>
@@ -85,7 +85,7 @@ By cloning its children, the `List` can pass extra information to every `Row` in
8585
</List>
8686
```
8787
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:
8989
9090
<Sandpack>
9191
@@ -180,21 +180,21 @@ button {
180180
181181
</Sandpack>
182182
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.
184184
185185
<Pitfall>
186186
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).
188188
189189
</Pitfall>
190190
191191
---
192192
193-
## Alternatives {/*alternatives*/}
193+
## Alternativas {/*alternatives*/}
194194
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*/}
196196
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:
198198
199199
```js {1,7}
200200
export default function List({ items, renderItem }) {
@@ -207,7 +207,7 @@ export default function List({ items, renderItem }) {
207207
})}
208208
```
209209
210-
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:
211211
212212
```js {3,7}
213213
<List
@@ -222,7 +222,7 @@ The `renderItem` prop is called a "render prop" because it's a prop that specifi
222222
/>
223223
```
224224
225-
The end result is the same as with `cloneElement`:
225+
El resultado final es el mismo que con `cloneElement`:
226226
227227
```js {4,8,12}
228228
<List>
@@ -241,7 +241,7 @@ The end result is the same as with `cloneElement`:
241241
</List>
242242
```
243243
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`.
245245
246246
<Sandpack>
247247
@@ -337,22 +337,22 @@ button {
337337
338338
</Sandpack>
339339
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.
341341
342342
---
343343
344-
### Passing data through context {/*passing-data-through-context*/}
344+
### Pasando datos a través del contexto {/*passing-data-through-context*/}
345345
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)
347347
348348
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`:
350350
351351
```js
352352
export const HighlightContext = createContext(false);
353353
```
354354
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`:
356356
357357
```js {8,10}
358358
export default function List({ items, renderItem }) {
@@ -369,15 +369,15 @@ export default function List({ items, renderItem }) {
369369
})}
370370
```
371371
372-
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:
373373
374374
```js Row.js {2}
375375
export default function Row({ title }) {
376376
const isHighlighted = useContext(HighlightContext);
377377
// ...
378378
````
379379

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

382382
```js {4}
383383
<List
@@ -388,7 +388,7 @@ This allows the calling component to not know or worry about passing `isHighligh
388388
/>
389389
```
390390

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

393393
<Sandpack>
394394

@@ -498,13 +498,13 @@ button {
498498

499499
</Sandpack>
500500

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)
502502

503503
---
504504

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*/}
506506

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

509509
```js
510510
import { useState } from 'react';
@@ -523,7 +523,7 @@ export default function useList(items) {
523523
}
524524
```
525525

526-
Then you could use it like this:
526+
Entonces puedes usarlo así:
527527

528528
```js {2,9,13}
529529
export default function App() {
@@ -546,7 +546,7 @@ export default function App() {
546546
}
547547
```
548548

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

551551
<Sandpack>
552552

@@ -639,15 +639,15 @@ button {
639639

640640
</Sandpack>
641641

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

644644
---
645645

646-
## Reference {/*reference*/}
646+
## Referencia {/*reference*/}
647647

648648
### `cloneElement(element, props, ...children)` {/*cloneelement*/}
649649

650-
Call `cloneElement` to create a React element based on the `element`, but with different `props` and `children`:
650+
Llama a `cloneElement` para crear un elemento React basado en el `element`, pero con diferentes `props` y `children`:
651651

652652
```js
653653
import { cloneElement } from 'react';
@@ -664,31 +664,31 @@ const clonedElement = cloneElement(
664664
console.log(clonedElement); // <Row title="Cabbage">Goodbye</Row>
665665
```
666666

667-
[See more examples above.](#usage)
667+
[Ver más ejemplos arriba.](#usage)
668668

669-
#### Parameters {/*parameters*/}
669+
#### Parámetros {/*parameters*/}
670670

671-
* `element`: The `element` argument must be a valid React element. For example, it could be a JSX node 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 lido. Por ejemplo, podría ser un nodo JSX como `<Something />`, el resultado de llamar a [`createElement`](/apis/react/createElement), o el resultado de otra llamada a `cloneElement`.
672672

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

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

677-
#### Returns {/*returns*/}
677+
#### Devuelve {/*returns*/}
678678

679-
`cloneElement` returns a React element object with a few properties:
679+
`cloneElement` devuelve un objeto de elemento React con algunas propiedades:
680680

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

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

688-
#### Caveats {/*caveats*/}
688+
#### Advertencias {/*advertencias*/}
689689

690-
* Cloning an element **does not modify the original element.**
690+
* Clonar un elemento **no modifica el elemento original.**
691691

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

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

Comments
 (0)