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
Copy file name to clipboardExpand all lines: src/content/reference/react/useImperativeHandle.md
+28-21Lines changed: 28 additions & 21 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,10 +1,17 @@
1
1
---
2
2
title: useImperativeHandle
3
+
translationStatus: ai-draft
3
4
---
4
5
6
+
<Note>
7
+
8
+
Questa pagina è stata tradotta automaticamente e supervisionata da un maintainer. Un'ulteriore revisione da parte della community sarebbe comunque utile. [Migliora questa traduzione](https://github.com/reactjs/it.react.dev/edit/main/src/content/reference/react/useImperativeHandle.md).
9
+
10
+
</Note>
11
+
5
12
<Intro>
6
13
7
-
`useImperativeHandle`is a React Hook that lets you customize the handle exposed as a[ref.](/learn/manipulating-the-dom-with-refs)
14
+
`useImperativeHandle`è un Hook React che ti permette di personalizzare l'handle esposto come[ref.](/learn/manipulating-the-dom-with-refs)
Call`useImperativeHandle`at the top level of your component to customize the ref handle it exposes:
30
+
Chiama`useImperativeHandle`al top level del tuo componente per personalizzare l'handle del ref che espone:
24
31
25
32
```js
26
33
import { useImperativeHandle } from'react';
27
34
28
35
functionMyInput({ ref }) {
29
36
useImperativeHandle(ref, () => {
30
37
return {
31
-
// ... your methods ...
38
+
// ... i tuoi metodi ...
32
39
};
33
40
}, []);
34
41
// ...
35
42
```
36
43
37
-
[See more examples below.](#usage)
44
+
[Vedi altri esempi sotto.](#usage)
38
45
39
46
#### Parameters {/*parameters*/}
40
47
41
-
* `ref`: The`ref`you received as a prop to the`MyInput` component.
48
+
* `ref`: La`ref`che hai ricevuto come prop del componente`MyInput`.
42
49
43
-
* `createHandle`: A function that takes no arguments and returns the ref handle you want to expose. That ref handle can have any type. Usually, you will return an object with the methods you want to expose.
50
+
* `createHandle`: Una funzione che non accetta argomenti e restituisce l'handle del ref che vuoi esporre. L'handle del ref può essere di qualsiasi tipo. Di solito, restituirai un oggetto con i metodi che vuoi esporre.
44
51
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. If a re-render resulted in a change to some dependency, or if you omitted this argument, your `createHandle`function will re-execute, and the newly created handle will be assigned to the ref.
52
+
* **optional** `dependencies`: L'elenco di tutti i valori reattivi referenziati all'interno del codice di `createHandle`. I valori reattivi includono props, state e tutte le variabili e funzioni dichiarate direttamente nel corpo del componente. Se il tuo linter è [configurato per React](/learn/editor-setup#linting), verificherà che ogni valore reattivo sia specificato correttamente come dipendenza. L'elenco delle dipendenze deve avere un numero costante di elementi ed essere scritto inline come`[dep1, dep2, dep3]`. React confronterà ogni dipendenza con il suo valore precedente usando il confronto [`Object.is`](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Se una ri-renderizzazione ha comportato un cambiamento in qualche dipendenza, o se hai omesso questo argomento, la tua funzione `createHandle`verrà rieseguita e l'handle appena creato verrà assegnato alla ref.
46
53
47
54
<Note>
48
55
49
-
Starting with React 19, [`ref`is available as a prop.](/blog/2024/12/05/react-19#ref-as-a-prop) In React 18 and earlier, it was necessary to get the `ref`from [`forwardRef`.](/reference/react/forwardRef)
56
+
A partire da React 19, [`ref`è disponibile come prop.](/blog/2024/12/05/react-19#ref-as-a-prop) In React 18 e versioni precedenti, era necessario ottenere la `ref`da [`forwardRef`.](/reference/react/forwardRef)
50
57
51
58
</Note>
52
59
53
60
#### Returns {/*returns*/}
54
61
55
-
`useImperativeHandle`returns`undefined`.
62
+
`useImperativeHandle`restituisce`undefined`.
56
63
57
64
---
58
65
59
66
## Usage {/*usage*/}
60
67
61
-
### Exposing a custom ref handle to the parent component {/*exposing-a-custom-ref-handle-to-the-parent-component*/}
68
+
### Esporre un handle ref personalizzato al componente genitore {/*exposing-a-custom-ref-handle-to-the-parent-component*/}
62
69
63
-
To expose a DOM node to the parent element, pass in the`ref`prop to the node.
70
+
Per esporre un nodo DOM al componente genitore, passa la prop`ref`al nodo.
64
71
65
72
```js {2}
66
73
functionMyInput({ ref }) {
67
74
return<input ref={ref} />;
68
75
};
69
76
```
70
77
71
-
With the code above, [a ref to`MyInput`will receive the `<input>` DOM node.](/learn/manipulating-the-dom-with-refs) However, you can expose a custom value instead. To customize the exposed handle, call`useImperativeHandle`at the top level of your component:
78
+
Con il codice sopra, [una ref a`MyInput`riceverà il nodo DOM `<input>`.](/learn/manipulating-the-dom-with-refs) Tuttavia, puoi esporre un valore personalizzato al suo posto. Per personalizzare l'handle esposto, chiama`useImperativeHandle`al top level del tuo componente:
72
79
73
80
```js {4-8}
74
81
import { useImperativeHandle } from'react';
75
82
76
83
functionMyInput({ ref }) {
77
84
useImperativeHandle(ref, () => {
78
85
return {
79
-
// ... your methods ...
86
+
// ... i tuoi metodi ...
80
87
};
81
88
}, []);
82
89
83
90
return<input />;
84
91
};
85
92
```
86
93
87
-
Note that in the code above, the`ref`is no longer passed to the `<input>`.
94
+
Nota che nel codice sopra, la`ref`non viene più passata all'`<input>`.
88
95
89
-
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:
96
+
Ad esempio, supponiamo che tu non voglia esporre l'intero nodo DOM `<input>`, ma che tu voglia esporre due dei suoi metodi: `focus`e`scrollIntoView`. Per farlo, mantieni il DOM del browser reale in una ref separata. Poi usa`useImperativeHandle`per esporre un handle con solo i metodi che vuoi che il componente genitore chiami:
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.
119
+
Ora, se il componente genitore ottiene una ref a`MyInput`, sarà in grado di chiamare i metodi`focus`e`scrollIntoView`su di esso. Tuttavia, non avrà pieno accesso al nodo DOM `<input>`sottostante.
113
120
114
121
<Sandpack>
115
122
@@ -122,7 +129,7 @@ export default function Form() {
122
129
123
130
functionhandleClick() {
124
131
ref.current.focus();
125
-
//This won't work because the DOM node isn't exposed:
132
+
//Non funzionerà perché il nodo DOM non è esposto:
126
133
// ref.current.style.opacity = 0.5;
127
134
}
128
135
@@ -170,9 +177,9 @@ input {
170
177
171
178
---
172
179
173
-
### Exposing your own imperative methods {/*exposing-your-own-imperative-methods*/}
180
+
### Esporre i tuoi metodi imperativi {/*exposing-your-own-imperative-methods*/}
174
181
175
-
The methods you expose via an imperative handle don't have to match the DOM methods exactly. For example, this `Post`component 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:
182
+
I metodi che esponi tramite un handle imperativo non devono corrispondere esattamente ai metodi del DOM. Ad esempio, questo componente `Post`espone un metodo`scrollAndFocusAddComment`tramite un handle imperativo. Questo permette al componente genitore `Page`di scorrere l'elenco dei commenti *e* mettere il focus sul campo di input quando clicchi su un pulsante:
176
183
177
184
<Sandpack>
178
185
@@ -285,8 +292,8 @@ export default AddComment;
285
292
286
293
<Pitfall>
287
294
288
-
**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.
295
+
**Non abusare delle ref.** Dovresti usare le ref solo per comportamenti *imperativi* che non puoi esprimere come props: ad esempio, scorrere fino a un nodo, mettere il focus su un nodo, attivare un'animazione, selezionare del testo, e così via.
289
296
290
-
**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.
297
+
**Se puoi esprimere qualcosa come prop, non dovresti usare una ref.** Ad esempio, invece di esporre un handle imperativo come `{ open, close }`da un componente `Modal`, è meglio accettare `isOpen`come prop, come`<Modal isOpen={isOpen} />`. Gli [Effetti](/learn/synchronizing-with-effects) possono aiutarti a esporre comportamenti imperativi tramite props.
0 commit comments