Skip to content

Commit a6577c3

Browse files
luiserdefcarburo
andauthored
Translate useImperativeHandle (#620)
* translate reference and exposing a custom ref handle to the parent component * add translation for Exposing your own imperative methods * modify translation manipular to identificador * minimal change changes * change titles to infinitive form * Update useImperativeHandle.md --------- Co-authored-by: Rainer Martinez <[email protected]> Co-authored-by: Rainer Martinez <[email protected]>
1 parent f321c1f commit a6577c3

File tree

1 file changed

+29
-29
lines changed

1 file changed

+29
-29
lines changed

beta/src/content/reference/react/useImperativeHandle.md

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ title: useImperativeHandle
44

55
<Intro>
66

7-
`useImperativeHandle` is a React Hook that lets you customize the handle exposed as a [ref.](/learn/manipulating-the-dom-with-refs)
7+
`useImperativeHandle` es un Hook de React que te permite personalizar el identificador expuesto como una [ref.](/learn/manipulating-the-dom-with-refs)
88

99
```js
1010
useImperativeHandle(ref, createHandle, dependencies?)
@@ -16,45 +16,45 @@ useImperativeHandle(ref, createHandle, dependencies?)
1616
1717
---
1818
19-
## Reference {/*reference*/}
19+
## Referencia {/*reference*/}
2020
2121
### `useImperativeHandle(ref, createHandle, dependencies?)` {/*useimperativehandle*/}
2222
23-
Call `useImperativeHandle` at the top level of your component to customize the ref handle it exposes:
23+
Llama a `useImperativeHandle` en el nivel superior de tu componente para personalizar el identificador ref que se expone:
2424
2525
```js
2626
import { forwardRef, useImperativeHandle } from 'react';
2727

2828
const MyInput = forwardRef(function MyInput(props, ref) {
2929
useImperativeHandle(ref, () => {
3030
return {
31-
// ... your methods ...
31+
// ... tus métodos ...
3232
};
3333
}, []);
3434
// ...
3535
```
3636
37-
[See more examples below.](#usage)
37+
[Mira más ejemplos debajo.](#usage)
3838
39-
#### Parameters {/*parameters*/}
39+
#### Parámetros {/*parameters*/}
4040
41-
* `ref`: The `ref` you received as the second argument from the [`forwardRef` render function.](/reference/react/forwardRef#render-function)
41+
* `ref`: La `ref` que recibes como segundo argumento de la [función render `forwardRef`](/reference/react/forwardRef#render-function)
4242
43-
* `createHandle`: A function that takes no arguments and returns the ref handle you want to expose. The ref handle you return can have any type. Usually, you will return an object with the methods you want to expose.
43+
* `createHandle`: Una función que no toma argumentos y devuelve el identificador ref que quieres exponer. El identificador ref que devuelve puede tener cualquier tipo. Por lo general, devolverá un objeto con lo métodos que quieres exponer.
4444
45-
* **optional** `dependencies`: The list of all reactive values referenced inside of the `createHandle` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If a re-render resulted in a change to some dependency, or if you did not specify the dependencies at all, your `createHandle` function will re-execute, and the newly created handle will be assigned to the ref.
45+
* **opcional** `dependencies`: La lista de todos los valores reactivos a los que se hace referencia dentro del código de `createHandle`. Los valores reactivos incluye props, estados, y todas las variables y funciones declaradas directamente dentro del cuerpo de tu componente. Si tu linter es [configurado por React](/learn/editor-setup#linting), va a verificar que cada valor reactivo esté correctamente especificado como una dependencia. La lista de dependencias deben tener un número constante de elementos y ser escritos en una sola linea como `[dep1, dep2, dep3]`. React comparará cada dependencia con su valor anterior usando el algoritmo de comparación [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Si un nuevo renderizado resultara en un cambio a una dependencia, o si no especificaste las dependencias completamente, tu función `createHandle` se volverá a ejecutar, y el nuevo identificador recién creado será asignado a ref.
4646
47-
#### Returns {/*returns*/}
47+
#### Devuelve {/*returns*/}
4848
49-
`useImperativeHandle` returns `undefined`.
49+
`useImperativeHandle` devuelve `undefined`.
5050
5151
---
5252
53-
## Usage {/*usage*/}
53+
## Uso {/*usage*/}
5454
55-
### Exposing a custom ref handle to the parent component {/*exposing-a-custom-ref-handle-to-the-parent-component*/}
55+
### Exponer un identificador ref personalizado al componente padre {/*exposing-a-custom-ref-handle-to-the-parent-component*/}
5656
57-
By default, components don't expose their DOM nodes to parent components. For example, if you want the parent component of `MyInput` to [have access](/learn/manipulating-the-dom-with-refs) to the `<input>` DOM node, you have to opt in with [`forwardRef`:](/reference/react/forwardRef)
57+
Los componentes por defecto no exponen sus nodos DOM a los componentes padre. Por ejemplo, si quieres el componente padre de `MyInput` para [tener acceso](/learn/manipulating-the-dom-with-refs) al nodo DOM de `<input>`, tienes que optar por [`forwardRef`:](/reference/react/forwardRef)
5858
5959
```js {4}
6060
import { forwardRef } from 'react';
@@ -64,25 +64,25 @@ const MyInput = forwardRef(function MyInput(props, ref) {
6464
});
6565
```
6666
67-
With the code above, [a ref to `MyInput` will receive the `<input>` DOM node.](/reference/react/forwardRef#exposing-a-dom-node-to-the-parent-component) However, you can expose a custom value instead. To customize the exposed handle, call `useImperativeHandle` at the top level of your component:
67+
Con el código de arriba, [una ref a `MyInput` va a recibir el nodo DOM de `<input>`.](/reference/react/forwardRef#exposing-a-dom-node-to-the-parent-component) Aun así, puedes exponer un valor personalizado en su lugar. Para personalizar el identificador expuesto, llama a `useImperativeHandle` en el nivel superior de tu componente:
6868
6969
```js {4-8}
7070
import { forwardRef, useImperativeHandle } from 'react';
7171

7272
const MyInput = forwardRef(function MyInput(props, ref) {
7373
useImperativeHandle(ref, () => {
7474
return {
75-
// ... your methods ...
75+
// ... tus métodos ...
7676
};
7777
}, []);
7878

7979
return <input {...props} />;
8080
});
8181
```
8282
83-
Note that in the code above, the `ref` is no longer forwarded to the `<input>`.
83+
Ten en cuenta que en el código de arriba, la `ref` ya no se reenvía a `<input>`.
8484
85-
For example, suppose you don't want to expose the entire `<input>` DOM node, but you want to expose two of its methods: `focus` and `scrollIntoView`. To do this, keep the real browser DOM in a separate ref. Then use `useImperativeHandle` to expose a handle with only the methods that you want the parent component to call:
85+
Por ejemplo, supongamos que no quieres exponer el nodo DOM entero de `<input>`, pero quieres exponer dos de sus métodos: `focus` y `scrollIntoView`. Para hacer esto, mantén el DOM real del navegador en una ref separada. Entonces usa `useImperativeHandle` para exponer un identificador solamente con los métodos que quieres que el componente padre llame:
8686
8787
```js {7-14}
8888
import { forwardRef, useRef, useImperativeHandle } from 'react';
@@ -105,7 +105,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
105105
});
106106
```
107107
108-
Now, if the parent component gets a ref to `MyInput`, it will be able to call the `focus` and `scrollIntoView` methods on it. However, it will not have full access to the underlying `<input>` DOM node.
108+
Ahora, si el componente padre obtiene una ref a `MyInput`, podrá llamar a los métodos `focus` y `scrollIntoView` en él. Sin embargo, no va a tener acceso completo al nodo DOM de `<input>` de manera más profunda.
109109
110110
<Sandpack>
111111
@@ -118,15 +118,15 @@ export default function Form() {
118118

119119
function handleClick() {
120120
ref.current.focus();
121-
// This won't work because the DOM node isn't exposed:
121+
//Esto no funcionará porque el nodo DOM no está expuesto
122122
// ref.current.style.opacity = 0.5;
123123
}
124124

125125
return (
126126
<form>
127127
<MyInput label="Enter your name:" ref={ref} />
128128
<button type="button" onClick={handleClick}>
129-
Edit
129+
Editar
130130
</button>
131131
</form>
132132
);
@@ -166,9 +166,9 @@ input {
166166
167167
---
168168
169-
### Exposing your own imperative methods {/*exposing-your-own-imperative-methods*/}
169+
### Exponer tus propios métodos imperativos {/*exposing-your-own-imperative-methods*/}
170170
171-
The methods you expose via an imperative handle don't have to match the DOM methods exactly. For example, the `Post` component in the example below exposes a `scrollAndFocusAddComment` method via an imperative handle. This lets the parent `Page` scroll the list of comments *and* focus the input field when you click the button:
171+
Los métodos que expones a través de un identificador imperativo no tienen que coincidir exactamente a los métodos del DOM. Por ejemplo, el componente `Post` en el ejemplo de abajo expone a `scrollAndFocusAddComment` por medio de un identificador imperativo. Esto le permite a la `Página` padre desplazar la lista de comentarios *y* enfocar el campo de entrada cuando haces click al botón.
172172
173173
<Sandpack>
174174
@@ -186,7 +186,7 @@ export default function Page() {
186186
return (
187187
<>
188188
<button onClick={handleClick}>
189-
Write a comment
189+
Escribe un comentario
190190
</button>
191191
<Post ref={postRef} />
192192
</>
@@ -215,7 +215,7 @@ const Post = forwardRef((props, ref) => {
215215
return (
216216
<>
217217
<article>
218-
<p>Welcome to my blog!</p>
218+
<p>Bienvenidos a mi blog!</p>
219219
</article>
220220
<CommentList ref={commentsRef} />
221221
<AddComment ref={addCommentRef} />
@@ -244,7 +244,7 @@ const CommentList = forwardRef(function CommentList(props, ref) {
244244

245245
let comments = [];
246246
for (let i = 0; i < 50; i++) {
247-
comments.push(<p key={i}>Comment #{i}</p>);
247+
comments.push(<p key={i}>Comentario #{i}</p>);
248248
}
249249

250250
return (
@@ -261,7 +261,7 @@ export default CommentList;
261261
import { forwardRef, useRef, useImperativeHandle } from 'react';
262262

263263
const AddComment = forwardRef(function AddComment(props, ref) {
264-
return <input placeholder="Add comment..." ref={ref} />;
264+
return <input placeholder="Añadir comentario..." ref={ref} />;
265265
});
266266

267267
export default AddComment;
@@ -281,8 +281,8 @@ export default AddComment;
281281
282282
<Pitfall>
283283
284-
**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.
284+
**No sobreutilizar las refs.** Solo debes usar las refs para comportamientos *imperativos* que no puedes expresar como props: por ejemplo desplazarse a un nodo, enfocar un nodo, activar una animación, seleccionar texto, etc.
285285
286-
**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.
286+
**Si puedes expresar algo como una prop, no deberias usar una ref.** Por ejemplo, en vez de exponer un identificador imperativo como `{ open, close }` del componente `Modal`, es mejor tomar `isOpen` como una prop, algo como `<Modal isOpen={isOpen} />`. [Efectos](/learn/synchronizing-with-effects) puede ayudarte a exponer comportamientos imperativos via props.
287287
288288
</Pitfall>

0 commit comments

Comments
 (0)