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
### 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*/}
22
22
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()`:
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.
77
77
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.
79
79
80
-
<Recipestitle="Examples of forwarding a ref">
80
+
<Recipestitle="Ejemplos del paso de una ref">
81
81
82
-
#### Focusing a text input {/*focusing-a-text-input*/}
82
+
#### Enfocar una entrada de texto {/*focusing-a-text-input*/}
83
83
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>`.
85
85
86
86
<Sandpack>
87
87
@@ -133,9 +133,9 @@ input {
133
133
134
134
<Solution />
135
135
136
-
#### Playing and pausing a video {/*playing-and-pausing-a-video*/}
136
+
#### Reproducir y pausar un vídeo {/*playing-and-pausing-a-video*/}
137
137
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>`.
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>`:
214
214
215
215
```js {2,5,10}
216
216
functionForm() {
@@ -231,7 +231,7 @@ function Form() {
231
231
}
232
232
```
233
233
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.
235
235
236
236
237
237
<Sandpack>
@@ -309,9 +309,9 @@ input, button {
309
309
310
310
---
311
311
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*/}
313
313
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:
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`:
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.
350
350
351
351
<Sandpack>
352
352
@@ -405,23 +405,23 @@ input {
405
405
406
406
</Sandpack>
407
407
408
-
[Read more about using imperative handles.](/apis/react/useImperativeHandle)
408
+
[Más información sobre el uso de manejadores imperativos.](/apis/react/useImperativeHandle)
409
409
410
410
<Pitfall>
411
411
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.
413
413
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.
415
415
416
416
</Pitfall>
417
417
418
418
---
419
419
420
-
## Reference {/*reference*/}
420
+
## Referencias {/*reference*/}
421
421
422
422
### `forwardRef(render)` {/*forwardref*/}
423
423
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:
*`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.
438
438
439
-
#### Returns {/*returns*/}
439
+
#### Devuelve {/*returns*/}
440
440
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`.
442
442
443
-
#### Caveats {/*caveats*/}
443
+
#### Advertencias {/*caveats*/}
444
444
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.
446
446
447
447
448
448
---
449
449
450
-
### `render` function {/*render-function*/}
450
+
### Función `render` {/*render-function*/}
451
451
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`:
*`props`: The props passed by the parent component.
467
+
*`props`: Las props pasadas por el componente padre.
468
468
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)
470
470
471
-
#### Returns {/*render-returns*/}
471
+
#### Devuelve {/*render-returns*/}
472
472
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`.
474
474
475
475
---
476
476
477
-
## Troubleshooting {/*troubleshooting*/}
477
+
## Solución de problemas {/*troubleshooting*/}
478
478
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*/}
480
480
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.
482
482
483
-
For example, this component doesn't do anything with its`ref`:
483
+
Por ejemplo, este componente no hace nada con su`ref`:
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:
0 commit comments