Skip to content

Commit 39e02e8

Browse files
Alanch8carburo
andauthored
Translate forwardRef (#574)
* forwardRef * Update forwardRef.md Co-authored-by: Rainer Martínez Fraga <[email protected]>
1 parent 57eb6ba commit 39e02e8

File tree

1 file changed

+46
-46
lines changed

1 file changed

+46
-46
lines changed

Diff for: beta/src/content/apis/react/forwardRef.md

+46-46
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ title: forwardRef
44

55
<Intro>
66

7-
`forwardRef` lets your component expose a DOM node to parent component with a [ref.](/learn/manipulating-the-dom-with-refs)
7+
`forwardRef` le permite a tu componente exponer un nodo DOM al componente padre con una [ref.](/learn/manipulating-the-dom-with-refs)
88

99
```js
1010
const SomeComponent = forwardRef(render)
@@ -16,11 +16,11 @@ const SomeComponent = forwardRef(render)
1616

1717
---
1818

19-
## Usage {/*usage*/}
19+
## Uso {/*usage*/}
2020

21-
### Exposing a DOM node to the parent component {/*exposing-a-dom-node-to-the-parent-component*/}
21+
### Exponer un nodo DOM al componente padre {/*exposing-a-dom-node-to-the-parent-component*/}
2222

23-
By default, each component's DOM nodes are private. However, sometimes it's useful to expose a DOM node to the parent--for example, to allow focusing it. To opt in, wrap your component definition into `forwardRef()`:
23+
Por defecto, los nodos DOM de cada componente son privados. Sin embargo, a veces es útil exponer un nodo DOM al padre, por ejemplo, para permitir enfocarlo. Para permitirlo, envuelve la definición de tu componente con `forwardRef()`:
2424

2525
```js {3,11}
2626
import { forwardRef } from 'react';
@@ -36,7 +36,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
3636
});
3737
```
3838

39-
You will receive a <CodeStep step={1}>ref</CodeStep> as the second argument after props. Pass it to the DOM node that you want to expose:
39+
Recibirás una <CodeStep step={1}>ref</CodeStep> como segundo argumento después de props. Pásala al nodo DOM que quieras exponer:
4040

4141
```js {8} [[1, 3, "ref"], [1, 8, "ref", 30]]
4242
import { forwardRef } from 'react';
@@ -52,7 +52,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
5252
});
5353
```
5454

55-
This lets the parent `Form` component access the <CodeStep step={2}>`<input>` DOM node</CodeStep> exposed by `MyInput`:
55+
Esto permite al componente padre `Form` acceder al <CodeStep step={2}>`<input>` nodo DOM</CodeStep> expuesto por `MyInput`:
5656

5757
```js [[1, 2, "ref"], [1, 10, "ref", 41], [2, 5, "ref.current"]]
5858
function Form() {
@@ -73,15 +73,15 @@ function Form() {
7373
}
7474
```
7575

76-
This `Form` component [passes a ref](/apis/useref#manipulating-the-dom-with-a-ref) to `MyInput`. The `MyInput` component *forwards* that ref to the `<input>` browser tag. As a result, the `Form` component can access that `<input>` DOM node and call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on it.
76+
Este componente `Form` [pasa una ref](/apis/useref#manipulating-the-dom-with-a-ref) a `MyInput`. El componente `MyInput` *pasa* esa ref a la etiqueta `<input>` del navegador. Como resultado, el componente `Form` puede acceder a ese nodo DOM `<input>` y llamar a [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) en él.
7777

78-
Keep in mind that by exposing a ref to the DOM node inside your component, you're making it harder to change your component's internals later. You will typically expose DOM nodes from reusable low-level components like buttons or text inputs, but you won't do it for application-level components like an avatar or a comment.
78+
Ten en cuenta que al exponer una ref al nodo DOM dentro de tu componente, estás dificultando la posibilidad de cambiar el interior de tu componente más adelante. Por lo general, expondrás los nodos DOM de los componentes reutilizables de bajo nivel como los botones o las entradas de texto, pero no lo harás para los componentes de nivel de aplicación como un avatar o un comentario.
7979

80-
<Recipes title="Examples of forwarding a ref">
80+
<Recipes title="Ejemplos del paso de una ref">
8181

82-
#### Focusing a text input {/*focusing-a-text-input*/}
82+
#### Enfocar una entrada de texto {/*focusing-a-text-input*/}
8383

84-
Clicking the button will focus the input. The `Form` component defines a ref and passes it to the `MyInput` component. The `MyInput` component fowards that ref to the browser `<input>`. This lets the `Form` component focus the `<input>`.
84+
Al hacer clic en el botón el campo de texto (_input_) tomará el foco. El componente `Form` define una ref y la pasa al componente `MyInput`. El componente `MyInput` la reenvía al elemento nativo `<input>`. Esto permite que el componente `Form` enfoque el `<input>`.
8585

8686
<Sandpack>
8787

@@ -133,9 +133,9 @@ input {
133133

134134
<Solution />
135135

136-
#### Playing and pausing a video {/*playing-and-pausing-a-video*/}
136+
#### Reproducir y pausar un vídeo {/*playing-and-pausing-a-video*/}
137137

138-
Clicking the button will call [`play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) and [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) on a `<video>` DOM node. The `App` component defines a ref and passes it to the `MyVideoPlayer` component. The `MyVideoPlayer` component forwards that ref to the browser `<video>` node. This lets the `App` component play and pause the `<video>`.
138+
Al hacer clic en el botón, se llamará a [`play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) y [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) en un `<video>` del nodo DOM. El componente `App` define una ref y la pasa al componente `MyVideoPlayer`. El componente `MyVideoPlayer` pasa esa ref al nodo `<video>` del navegador. Esto permite al componente `App` reproducir y pausar el `<video>`.
139139

140140
<Sandpack>
141141

@@ -194,9 +194,9 @@ button { margin-bottom: 10px; margin-right: 10px; }
194194

195195
---
196196

197-
### Forwarding a ref through multiple components {/*forwarding-a-ref-through-multiple-components*/}
197+
### Pasar una ref a través de múltiples componentes {/*forwarding-a-ref-through-multiple-components*/}
198198

199-
Instead of forwarding a `ref` to a DOM node, you can forward it to your own component like `MyInput`:
199+
En lugar de pasar una `ref` a un nodo DOM, puedes pasarla a un componente propio como `MyInput`.:
200200

201201
```js {1,5}
202202
const FormField = forwardRef(function FormField(props, ref) {
@@ -210,7 +210,7 @@ const FormField = forwardRef(function FormField(props, ref) {
210210
});
211211
```
212212

213-
If that `MyInput` component forwards a ref to its `<input>`, a ref to `FormField` will give you that `<input>`:
213+
Si ese componente `MyInput` pasa una ref a su `<input>`, una ref a `FormField` te dará ese `<input>`:
214214

215215
```js {2,5,10}
216216
function Form() {
@@ -231,7 +231,7 @@ function Form() {
231231
}
232232
```
233233

234-
The `Form` component defines a ref and passes it to `FormField`. The `FormField` component forwards that ref to `MyInput`, which forwards this ref to a browser `<input>` DOM node. This is how `Form` accesses that DOM node.
234+
El componente `Form` del formulario define una ref y la pasa a `FormField`. El componente `FormField` pasa esa ref a `MyInput`, que a su vez la pasa a un nodo DOM `<input>`. Así es como `Form` accede a ese nodo DOM.
235235

236236

237237
<Sandpack>
@@ -309,9 +309,9 @@ input, button {
309309

310310
---
311311

312-
### Exposing an imperative handle instead of a DOM node {/*exposing-an-imperative-handle-instead-of-a-dom-node*/}
312+
### Exposición de un manejador imperativo en lugar de un nodo DOM {/*exposing-an-imperative-handle-instead-of-a-dom-node*/}
313313

314-
Instead of exposing an entire DOM node, you can expose a custom object, called an *imperative handle,* with a more constrained set of methods. To do this, you'd need to define a separate ref to hold the DOM node:
314+
En lugar de exponer un nodo DOM completo, puedes exponer un objeto personalizado, llamado manejador imperativo (*imperative handle*), con un conjunto de métodos más restringido. Para hacer esto, tendrías que definir una ref separada para guardar el nodo DOM:
315315

316316
```js {2,6}
317317
const MyInput = forwardRef(function MyInput(props, ref) {
@@ -323,7 +323,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
323323
});
324324
```
325325

326-
Then pass the `ref` you received to [`useImperativeHandle`](/apis/react/useImperativeHandle) and specify the value you want to expose to the `ref`:
326+
A continuación, pasa la `ref` que has recibido a [`useImperativeHandle`](/apis/react/useImperativeHandle) y especifica el valor que quieres exponer a la `ref`:
327327

328328
```js {6-15}
329329
import { forwardRef, useRef, useImperativeHandle } from 'react';
@@ -346,7 +346,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
346346
});
347347
```
348348

349-
If some component gets a ref to `MyInput` now, it will only receive your `{ focus, scrollIntoView }` object instead of the DOM node. This lets you limit the information you expose about your DOM node to the minimum.
349+
Si algún componente obtiene ahora una ref a `MyInput`, sólo recibirá su objeto `{ focus, scrollIntoView }` en lugar del nodo DOM. Esto te permite limitar la información que expones sobre tu nodo DOM al mínimo.
350350

351351
<Sandpack>
352352

@@ -405,23 +405,23 @@ input {
405405

406406
</Sandpack>
407407

408-
[Read more about using imperative handles.](/apis/react/useImperativeHandle)
408+
[Más información sobre el uso de manejadores imperativos.](/apis/react/useImperativeHandle)
409409

410410
<Pitfall>
411411

412-
**Do not overuse refs.** You should only use refs for *imperative* behaviors that you can't express as props: for example, scrolling to a node, focusing a node, triggering an animation, selecting text, and so on.
412+
**No abuses de las refs.** Sólo deberías usar refs para comportamientos *imperativos* que no puedes expresar como props: por ejemplo, desplazarse a un nodo, enfocar un nodo, desencadenar una animación, seleccionar texto, etc.
413413

414-
**If you can express something as a prop, you should not use a ref.** For example, instead of exposing an imperative handle like `{ open, close }` from a `Modal` component, it is better to take `isOpen` as a prop like `<Modal isOpen={isOpen} />`. [Effects](/learn/synchronizing-with-effects) can help you expose imperative behaviors via props.
414+
**Si puedes expresar algo como una prop, no debes usar una ref.** Por ejemplo, en lugar de exponer un manejador imperativo como `{ open, close }` de un componente `Modal`, es mejor tomar `isOpen` como prop `<Modal isOpen={isOpen} />`. [Effects](/learn/synchronizing-with-effects) puede ayudarte a exponer comportamientos imperativos a través de props.
415415

416416
</Pitfall>
417417

418418
---
419419

420-
## Reference {/*reference*/}
420+
## Referencias {/*reference*/}
421421

422422
### `forwardRef(render)` {/*forwardref*/}
423423

424-
Call `forwardRef()` to let your component receive a ref and forward it to a child component:
424+
Llama a `forwardRef()` para que tu componente reciba un ref y la reenvíe a un componente hijo:
425425

426426
```js
427427
import { forwardRef } from 'react';
@@ -432,24 +432,24 @@ const MyInput = forwardRef(function MyInput(props, ref) {
432432

433433
```
434434

435-
#### Parameters {/*parameters*/}
435+
#### Parámetros {/*parameters*/}
436436

437-
* `render`: The render function for your component. React calls this function with the props and `ref` that your component received from its parent. The JSX you return will be the output of your component.
437+
* `render`: La función de renderización de tu componente. React llama a esta función con las props y `ref` que tu componente recibió de su padre. El JSX que devuelve será la salida de tu componente.
438438

439-
#### Returns {/*returns*/}
439+
#### Devuelve {/*returns*/}
440440

441-
`forwardRef` returns a React component that you can render in JSX. Unlike React components defined as plain functions, a component returned by `forwardRef` is also able to receive a `ref` prop.
441+
`forwardRef` devuelve un componente de React que puedes renderizar en JSX. A diferencia de los componentes de React definidos como funciones simples, un componente devuelto por `forwardRef` también puede recibir una prop `ref`.
442442

443-
#### Caveats {/*caveats*/}
443+
#### Advertencias {/*caveats*/}
444444

445-
* In Strict Mode, React will **call your render function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your render function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.
445+
* En el modo estricto, React **llamará a tu función de renderizado dos veces** para [ayudarte a encontrar impurezas accidentales.](#my-initializer-or-updater-function-runs-twice) Este es un comportamiento sólo de desarrollo y no ocurre en producción. Si tu función de renderizado es pura (como debería ser), esto no debería afectar a la lógica de tu componente. El resultado de una de las llamadas será ignorado.
446446

447447

448448
---
449449

450-
### `render` function {/*render-function*/}
450+
### Función `render` {/*render-function*/}
451451

452-
`forwardRef` accepts a render function as an argument. React calls this function with `props` and `ref`:
452+
`forwardRef` acepta una función de renderizado como argumento. React llama a esta función con `props` y `ref`:
453453

454454
```js
455455
const MyInput = forwardRef(function MyInput(props, ref) {
@@ -462,25 +462,25 @@ const MyInput = forwardRef(function MyInput(props, ref) {
462462
});
463463
```
464464

465-
#### Parameters {/*render-parameters*/}
465+
#### Parámetros {/*render-parameters*/}
466466

467-
* `props`: The props passed by the parent component.
467+
* `props`: Las props pasadas por el componente padre.
468468

469-
* `ref`: The `ref` attribute passed by the parent component. The `ref` can be an object or a function. If the parent component has not passed a ref, it will be `null`. You should either pass the `ref` you receive to another component, or pass it to [`useImperativeHandle`.](/apis/react/useImperativeHandle)
469+
* `ref`: El atributo `ref` pasado por el componente padre. La `ref` puede ser un objeto o una función. Si el componente padre no ha pasado un ref, será `null`. Deberás pasar la "ref" que recibas o bien a otro componente, o bien a [`useImperativeHandle`.](/apis/react/useImperativeHandle)
470470

471-
#### Returns {/*render-returns*/}
471+
#### Devuelve {/*render-returns*/}
472472

473-
`forwardRef` returns a React component that you can render in JSX. Unlike React components defined as plain functions, the component returned by `forwardRef` is able to take a `ref` prop.
473+
`forwardRef` devuelve un componente de React que puedes renderizar en JSX. A diferencia de los componentes de React definidos como funciones simples, el componente devuelto por `forwardRef` puede tomar una prop `ref`.
474474

475475
---
476476

477-
## Troubleshooting {/*troubleshooting*/}
477+
## Solución de problemas {/*troubleshooting*/}
478478

479-
### My component is wrapped in `forwardRef`, but the `ref` to it is always `null` {/*my-component-is-wrapped-in-forwardref-but-the-ref-to-it-is-always-null*/}
479+
### Mi componente está envuelto en `forwardRef`, pero la `ref` a él es siempre `null`. {/*my-component-is-wrapped-in-forwardref-but-the-ref-to-it-is-always-null*/}
480480

481-
This usually means that you forgot to actually use the `ref` that you received.
481+
Esto suele significar que olvidaste utilizar la `ref` que recibiste.
482482

483-
For example, this component doesn't do anything with its `ref`:
483+
Por ejemplo, este componente no hace nada con su `ref`:
484484

485485
```js {1}
486486
const MyInput = forwardRef(function MyInput({ label }, ref) {
@@ -493,7 +493,7 @@ const MyInput = forwardRef(function MyInput({ label }, ref) {
493493
});
494494
```
495495

496-
To fix it, pass the `ref` down to a DOM node or another component that can accept a ref:
496+
Para solucionarlo, pasa la `ref` a un nodo DOM o a otro componente que pueda aceptar una ref:
497497

498498
```js {1,5}
499499
const MyInput = forwardRef(function MyInput({ label }, ref) {
@@ -506,7 +506,7 @@ const MyInput = forwardRef(function MyInput({ label }, ref) {
506506
});
507507
```
508508

509-
The `ref` to `MyInput` could also be `null` if some of the logic is conditional:
509+
La `ref` a `MyInput` también podría ser `null` si parte de la lógica es condicional:
510510

511511
```js {1,5}
512512
const MyInput = forwardRef(function MyInput({ label, showInput }, ref) {
@@ -519,7 +519,7 @@ const MyInput = forwardRef(function MyInput({ label, showInput }, ref) {
519519
});
520520
```
521521

522-
If `showInput` is `false`, then the ref won't be forwarded to any node, and a ref to `MyInput` will remain empty. This is particularly easy to miss if the condition is hidden inside another component, like `Panel` in this example:
522+
Si `showInput` es `false`, la ref no será reenviada a ningún nodo, y una ref a `MyInput` permanecerá vacía. Esto es particularmente fácil de pasar por alto si la condición está oculta dentro de otro componente, como `Panel` en este ejemplo:
523523

524524
```js {5,7}
525525
const MyInput = forwardRef(function MyInput({ label, showInput }, ref) {

0 commit comments

Comments
 (0)