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/learn/adding-interactivity.md
+51-51Lines changed: 51 additions & 51 deletions
Original file line number
Diff line number
Diff line change
@@ -1,30 +1,30 @@
1
1
---
2
-
title: Adding Interactivity
2
+
title: Aggiungere le Interazioni
3
3
---
4
4
5
5
<Intro>
6
6
7
-
Some things on the screen update in response to user input. For example, clicking an image gallery switches the active image. In React, data that changes over time is called *state.*You can add state to any component, and update it as needed. In this chapter, you'll learn how to write components that handle interactions, update their state, and display different output over time.
7
+
Alcune cose sullo schermo si aggiornano in risposta all'input dell'utente. Ad esempio, cliccare su una galleria d'immagini modifica l'immagine corrente. In React, i dati che cambiano nel tempo vengono chiamati *state.*Puoi aggiungere lo state a qualsiasi componente e aggiornarlo secondo necessità. In questo capitolo, imparerai a scrivere componenti che gestiscono interazioni, aggiornano il loro state, e visualizzano diversi output nel tempo.
8
8
9
9
</Intro>
10
10
11
11
<YouWillLearnisChapter={true}>
12
12
13
-
*[How to handle user-initiated events](/learn/responding-to-events)
14
-
*[How to make components "remember" information with state](/learn/state-a-components-memory)
15
-
*[How React updates the UI in two phases](/learn/render-and-commit)
16
-
*[Why state doesn't update right after you change it](/learn/state-as-a-snapshot)
17
-
*[How to queue multiple state updates](/learn/queueing-a-series-of-state-updates)
18
-
*[How to update an object in state](/learn/updating-objects-in-state)
19
-
*[How to update an array in state](/learn/updating-arrays-in-state)
13
+
*[Come gestire gli eventi originati dall'utente](/learn/responding-to-events)
14
+
*[Come far "ricordare" le informazioni ai componenti tramite lo state](/learn/state-a-components-memory)
15
+
*[Come React aggiorna la UI in due fasi](/learn/render-and-commit)
16
+
*[Perché lo state non si aggiorna subito dopo averlo modificato](/learn/state-as-a-snapshot)
17
+
*[Come accodare più aggiornamenti dello state](/learn/queueing-a-series-of-state-updates)
18
+
*[Come aggiornare un oggetto nello state](/learn/updating-objects-in-state)
19
+
*[Come aggiornare un array nello state](/learn/updating-arrays-in-state)
20
20
21
21
</YouWillLearn>
22
22
23
-
## Responding to events {/*responding-to-events*/}
23
+
## Rispondere agli Eventi {/*responding-to-events*/}
24
24
25
-
React lets you add *event handlers* to your JSX. Event handlers are your own functions that will be triggered in response to user interactions like clicking, hovering, focusing on form inputs, and so on.
25
+
React ti consente di aggiungere degli *event handler* al tuo JSX. Gli event handler sono le tue funzioni personalizzate che vengono chiamate in risposta alle interazioni dell'utente, come il click, il passaggio del mouse, la messa a fuoco delle input e così via.
26
26
27
-
Built-in components like`<button>`only support built-in browser events like `onClick`. However, you can also create your own components, and give their event handler props any application-specific names that you like.
27
+
Componenti integrati come`<button>`supportano solo eventi integrati del browser come `onClick`. Tuttavia, è possibile anche creare i propri componenti e dare ai loro event handler dei nomi specifici, contestualizzati all'applicazione.
Read**[Responding to Events](/learn/responding-to-events)**to learn how to add event handlers.
71
+
Leggi**[Rispondere agli Eventi](/learn/responding-to-events)**per imparare ad aggiungere gli event handler.
72
72
73
73
</LearnMore>
74
74
75
-
## State: a component's memory {/*state-a-components-memory*/}
75
+
## State: La Memoria di un Componente {/*state-a-components-memory*/}
76
76
77
-
Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" puts a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called*state.*
77
+
Spesso i componenti devono cambiare ciò che c'è sullo schermo in seguito a un'interazione. Scrivere nel form deve aggiornare l'input, cliccare "avanti" su un carosello deve cambiare l'immagine mostrata, cliccare "acquista" inserisce un prodotto nel carrello. I componenti devono "ricordare" le cose: l'attuale valore della input, l'attuale immagine, il carrello. In React, questo specifico tipo di memoria è detto*state.*
78
78
79
-
You can add state to a component with a [`useState`](/reference/react/useState) Hook. *Hooks* are special functions that let your components use React features (state is one of those features). The`useState`Hook lets you declare a state variable. It takes the initial state and returns a pair of values: the current state, and a state setter function that lets you update it.
79
+
Puoi aggiungere lo state a un componente con un hook [`useState`](/reference/react/useState). Gli *Hook* sono speciali funzioni che consentono ai componenti di usare le funzionalità di React (lo state è una di queste). L'hook`useState`consente di dichiarare una variabile state. Prende lo state iniziale e restituisce una coppia di valori: lo state attuale e una funzione *state setter* che consente di aggiornarlo.
80
80
81
81
```js
82
82
const [index, setIndex] =useState(0);
83
83
const [showMore, setShowMore] =useState(false);
84
84
```
85
85
86
-
Here is how an image gallery uses and updates state on click:
86
+
Ecco come una galleria di immagini usa e aggiorna lo state al click:
Read**[State: A Component's Memory](/learn/state-a-components-memory)**to learn how to remember a value and update it on interaction.
232
+
Leggi**[State: La Memoria di un Componente](/learn/state-a-components-memory)**per imparare a memorizzare un valore e aggiornarlo in base alle interazioni.
233
233
234
234
</LearnMore>
235
235
236
-
## Render and commit {/*render-and-commit*/}
236
+
## Renderizzazione e Commit {/*render-and-commit*/}
237
237
238
-
Before your components are displayed on the screen, they must be rendered by React. Understanding the steps in this process will help you think about how your code executes and explain its behavior.
238
+
Prima che i tuoi componenti siano visualizzati sullo schermo, devono essere renderizzati da React. Comprendere le fasi di questo processo ti aiuterà a riflettere su come viene eseguito il tuo codice e a spiegarne il comportamento.
239
239
240
-
Imagine that your components are cooks in the kitchen, assembling tasty dishes from ingredients. In this scenario, React is the waiter who puts in requests from customers and brings them their orders. This process of requesting and serving UI has three steps:
240
+
Immagina che i tuoi componenti siano cuochi in cucina, che assemblano deliziosi piatti. In questo scenario, React è il cameriere che prende le comande dai clienti e porta loro gli ordini. Questo processo di richiesta e servizio della UI ha tre fasi:
241
241
242
-
1.**Triggering**a render (delivering the diner's order to the kitchen)
243
-
2.**Rendering**the component (preparing the order in the kitchen)
244
-
3.**Committing**to the DOM (placing the order on the table)
242
+
1.**Triggerare**un render (portare la comanda in cucina)
243
+
2.**Renderizzare**il componente (preparare l'ordine in cucina)
244
+
3.**Committare i cambiamenti**al DOM (portare l'ordine al tavolo)
245
245
246
246
<IllustrationBlocksequential>
247
-
<Illustrationcaption="Trigger"alt="React as a server in a restaurant, fetching orders from the users and delivering them to the Component Kitchen."src="/images/docs/illustrations/i_render-and-commit1.png" />
248
-
<Illustrationcaption="Render"alt="The Card Chef gives React a fresh Card component."src="/images/docs/illustrations/i_render-and-commit2.png" />
249
-
<Illustrationcaption="Commit"alt="React delivers the Card to the user at their table."src="/images/docs/illustrations/i_render-and-commit3.png" />
247
+
<Illustrationcaption="Trigger"alt="React come cameriere in un ristorante, che prende le comande dagli utenti e li porta alla cucina dei componenti."src="/images/docs/illustrations/i_render-and-commit1.png" />
248
+
<Illustrationcaption="Renderizzazione"alt="Il cuoco Card consegna a React un nuovo componente Card."src="/images/docs/illustrations/i_render-and-commit2.png" />
249
+
<Illustrationcaption="Commit"alt="React porta la Card al tavolo dell'utente."src="/images/docs/illustrations/i_render-and-commit3.png" />
250
250
</IllustrationBlock>
251
251
252
252
<LearnMorepath="/learn/render-and-commit">
253
253
254
-
Read**[Render and Commit](/learn/render-and-commit)**to learn the lifecycle of a UI update.
254
+
Leggi**[Renderizzazione e Commit](/learn/render-and-commit)**per imparare il ciclo di vita di un aggiornamento UI.
255
255
256
256
</LearnMore>
257
257
258
-
## State as a snapshot {/*state-as-a-snapshot*/}
258
+
## Lo State come Istantanea {/*state-as-a-snapshot*/}
259
259
260
-
Unlike regular JavaScript variables, React state behaves more like a snapshot. Setting it does not change the state variable you already have, but instead triggers a re-render. This can be surprising at first!
260
+
A differenza delle normali variabili JavaScript, lo state di React si comporta più come un'istantanea. Impostarlo non modifica la variabile state che già possiedi, ma triggera un re-render. Questo può sorprendere all'inizio!
261
261
262
262
```js
263
263
console.log(count); // 0
264
-
setCount(count +1); //Request a re-render with 1
265
-
console.log(count); //Still 0!
264
+
setCount(count +1); //Richiedi un re-render con 1
265
+
console.log(count); //Ancora 0!
266
266
```
267
267
268
-
This behavior help you avoid subtle bugs. Here is a little chat app. Try to guess what happens if you press "Send" first and *then* change the recipient to Bob. Whose name will appear in the `alert`five seconds later?
268
+
Questo comportamento aiuta a evitare bug difficili da individuare. Ecco una piccola app di messaggistica. Prova a indovinare cosa succede se premi "Send" e *poi* selezioni il destinatario Bob. Quale nome apparirà nell'`alert`cinque secondi dopo?
[State as a Snapshot](/learn/state-as-a-snapshot)explains why this is happening. Setting state requests a new re-render, but does not change it in the already running code. So`score`continues to be`0`right after you call`setScore(score + 1)`.
357
+
[Lo State come Istantanea](/learn/state-as-a-snapshot)spiega a cosa è dovuto questo. Impostare lo state richiede un nuovo re-render, ma non lo modifica nel codice già eseguito. Quindi`score`continua a essere`0`subito dopo aver chiamato`setScore(score + 1)`.
You can fix this by passing an*updater function* when setting state. Notice how replacing`setScore(score + 1)`with`setScore(s => s + 1)`fixes the "+3" button. This lets you queue multiple state updates.
369
+
Puoi risolvere questo problema passando una funzione*updater* quando imposti lo state. Nota come sostituire`setScore(score + 1)`con`setScore(s => s + 1)`aggiusta il bottone "+3". Questo consente di accodare più aggiornamenti dello state.
Read**[Queueing a Series of State Updates](/learn/queueing-a-series-of-state-updates)**to learn how to queue a sequence of state updates.
405
+
Leggi**[Accodare più Aggiornamenti dello State](/learn/queueing-a-series-of-state-updates)**per imparare ad accodare una sequenza di aggiornamenti dello state.
406
406
407
407
</LearnMore>
408
408
409
-
## Updating objects in state {/*updating-objects-in-state*/}
409
+
## Aggiornare gli Oggetti nello State {/*updating-objects-in-state*/}
410
410
411
-
State can hold any kind of JavaScript value, including objects. But you shouldn't change objects and arrays that you hold in the React state directly. Instead, when you want to update an object and array, you need to create a new one (or make a copy of an existing one), and then update the state to use that copy.
411
+
Lo State può contenere qualsiasi tipo di valore JavaScript, inclusi gli oggetti. Tuttavia, non dovresti modificare direttamente gli oggetti e gli array contenuti nello State. Quando vuoi aggiornare un oggetto o un array, dovresti invece crearne uno nuovo (o copiare quello esistente) e, infine, impostare la copia nello state.
412
412
413
-
Usually, you will use the `...`spread syntax to copy objects and arrays that you want to change. For example, updating a nested object could look like this:
413
+
Solitamente, userai la sintassi di spread `...`per copiare gli oggetti e gli array che desideri modificare. Ad esempio, l'aggiornamento di un oggetto nidificato potrebbe apparire così:
If copying objects in code gets tedious, you can use a library like [Immer](https://github.com/immerjs/use-immer)to reduce repetitive code:
521
+
Se copiare gli oggetti diventa tedioso, puoi usare una libreria come [Immer](https://github.com/immerjs/use-immer)per ridurre il codice ripetitivo:
Read**[Updating Objects in State](/learn/updating-objects-in-state)**to learn how to update objects correctly.
636
+
Leggi**[Aggiornare gli Oggetti nello State](/learn/updating-objects-in-state)**per imparare ad aggiornare gli oggetti correttamente.
637
637
638
638
</LearnMore>
639
639
640
-
## Updating arrays in state {/*updating-arrays-in-state*/}
640
+
## Aggiornare gli Array nello State {/*updating-arrays-in-state*/}
641
641
642
-
Arrays are another type of mutable JavaScript objects you can store in state and should treat as read-only. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array:
642
+
Gli array sono un altro tipo di oggetti JavaScript mutabili che puoi memorizzare nello state e che dovresti trattare come read-only. Come per gli oggetti, quando vuoi aggiornare un array contenuto nello state, devi crearne uno nuovo (o copiare l'esistente), e infine impostare il nuovo array nello state.
643
643
644
644
<Sandpack>
645
645
@@ -706,7 +706,7 @@ function ItemList({ artworks, onToggle }) {
706
706
707
707
</Sandpack>
708
708
709
-
If copying arrays in code gets tedious, you can use a library like [Immer](https://github.com/immerjs/use-immer)to reduce repetitive code:
709
+
Se copiare gli array diventa tedioso, puoi usare una libreria come [Immer](https://github.com/immerjs/use-immer)per ridurre il codice ripetitivo:
710
710
711
711
<Sandpack>
712
712
@@ -791,12 +791,12 @@ function ItemList({ artworks, onToggle }) {
791
791
792
792
<LearnMorepath="/learn/updating-arrays-in-state">
793
793
794
-
Read**[Updating Arrays in State](/learn/updating-arrays-in-state)**to learn how to update arrays correctly.
794
+
Leggi**[Aggiornare gli Array nello State](/learn/updating-arrays-in-state)**per imparare ad aggiornare gli array correttamente.
795
795
796
796
</LearnMore>
797
797
798
-
## What's next? {/*whats-next*/}
798
+
## Qual è il Prossimo Passo? {/*whats-next*/}
799
799
800
-
Head over to [Responding to Events](/learn/responding-to-events)to start reading this chapter page by page!
800
+
Dirigiti su [Rispondere agli Eventi](/learn/responding-to-events)per iniziare a leggere questo capitolo pagina per pagina!
801
801
802
-
Or, if you're already familiar with these topics, why not read about [Managing State](/learn/managing-state)?
802
+
Oppure, se hai già familiarità con questi argomenti, perché non leggere [Gestire lo State](/learn/managing-state)?
0 commit comments