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: content/docs/forms.md
+87-76
Original file line number
Diff line number
Diff line change
@@ -9,30 +9,30 @@ redirect_from:
9
9
- "docs/forms-zh-CN.html"
10
10
---
11
11
12
-
HTML form elements work a little bit differently from other DOM elements in React, because form elements naturally keep some internal state. For example, this form in plain HTML accepts a single name:
12
+
Gli elementi HTML `form` funzionano in un modo un po' differente rispetto agli altri elementi DOM in React, la motivazione sta nel fatto che gli elementi form mantengono naturalmente uno stato interno. Ad esempio, questo form in puro HTML accetta un singolo nome:
13
13
14
14
```html
15
15
<form>
16
16
<label>
17
-
Name:
18
-
<inputtype="text"name="name" />
17
+
Nome:
18
+
<inputtype="text"name="nome" />
19
19
</label>
20
20
<inputtype="submit"value="Submit" />
21
21
</form>
22
22
```
23
23
24
-
This form has the default HTML form behavior of browsing to a new page when the user submits the form. If you want this behavior in React, it just works. But in most cases, it's convenient to have a JavaScript function that handles the submission of the form and has access to the data that the user entered into the form. The standard way to achieve this is with a technique called "controlled components".
24
+
Questo form si comporta come di consueto, facendo navigare l'utente in una nuova pagina quando viene inviato. In React, se vuoi avere lo stesso comportamento, non c'è bisogno di fare alcuna modifica. Ad ogni modo, potrebbe essere più conveniente avere una funzione JavaScript che gestisce l'invio del form e che ha accesso ai dati inseriti dall'utente. La tecnica standard con cui si può ottenere ciò prende il nome di "componenti controllati".
In HTML, form elements such as `<input>`, `<textarea>`, and`<select>`typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with[`setState()`](/docs/react-component.html#setstate).
28
+
In HTML, gli elementi di un form come `<input>`, `<textarea>` e`<select>`mantengono tipicamente il proprio stato e lo aggiornano in base all'input dell'utente. In React, lo stato mutabile viene tipicamente mantenuto nella proprietà `state` dei componenti e viene poi aggiornato solo mediante[`setState()`](/docs/react-component.html#setstate).
29
29
30
-
We can combine the two by making the React state be the "single source of truth". Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a "controlled component".
30
+
Possiamo combinare le due cose rendendo lo _state_ in React la "singola fonte attendibile" ([SSOT](https://en.wikipedia.org/wiki/Single_source_of_truth)). Possiamo poi fare in modo che il componente React che renderizza il form controlli anche cosa succede all'interno del form in risposta agli input dell'utente. In un form, un elemento di input il cui valore è controllato da React viene così chiamato "componente controllato".
31
31
32
-
For example, if we want to make the previous example log the name when it is submitted, we can write the form as a controlled component:
32
+
Ad esempio, se vogliamo far sì che l'esempio precedente registri il nome inserito, possiamo riscrivere il form sotto forma di componente controllato:
33
33
34
34
```javascript{4,10-12,24}
35
-
class NameForm extends React.Component {
35
+
class FormNome extends React.Component {
36
36
constructor(props) {
37
37
super(props);
38
38
this.state = {value: ''};
@@ -46,15 +46,15 @@ class NameForm extends React.Component {
46
46
}
47
47
48
48
handleSubmit(event) {
49
-
alert('A name was submitted: ' + this.state.value);
49
+
alert('E\' stato inserito un nome: ' + this.state.value);
@@ -64,36 +64,38 @@ class NameForm extends React.Component {
64
64
}
65
65
```
66
66
67
-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/VmmPgp?editors=0010)
67
+
**[Prova su CodeSandbox](codesandbox://forms/1.js)**
68
68
69
-
Since the `value`attribute is set on our form element, the displayed value will always be `this.state.value`, making the React state the source of truth. Since `handleChange`runs on every keystroke to update the React state, the displayed value will update as the user types.
69
+
Dato che l'attributo `value`viene impostato nel nostro elemento form, il valore visualizzato sarà sempre `this.state.value`, rendendo lo stato in React l'unica fonte di dati attendibile. Dato che la funzione `handleChange`viene eseguita ad ogni battitura per aggiornare lo stato di React, il valore visualizzato verrà aggiornato man mano che l'utente preme i tasti.
70
70
71
-
With a controlled component, every state mutation will have an associated handler function. This makes it straightforward to modify or validate user input. For example, if we wanted to enforce that names are written with all uppercase letters, we could write `handleChange`as:
71
+
Con un componente controllato, ogni mutazione dello stato deve aver associata una funzione _handler_. Tutto ciò rende il processo di modifica e la validazione dell'input dell'utente semplice e lineare. Ad esempio, se volessimo definire una regola che vuole che i nomi vengano sempre scritti tutti in maiuscolo, possiamo definire `handleChange`così:
In HTML, a`<textarea>`element defines its text by its children:
81
+
In HTML, l'elemento`<textarea>`definisce il testo in esso contenuto con i suoi elementi figli:
82
82
83
83
```html
84
84
<textarea>
85
-
Hello there, this is some text in a text area
85
+
Nel mezzo del cammin di nostra vita
86
+
mi ritrovai per una selva oscura
87
+
ché la diritta via era smarrita.
86
88
</textarea>
87
89
```
88
90
89
-
In React, a`<textarea>`uses a`value` attribute instead. This way, a form using a `<textarea>`can be written very similarly to a form that uses a single-line input:
91
+
In React, invece,`<textarea>`utilizza l'attributo`value`. Per questo, un form che utilizza una `<textarea>`può essere scritto in modo molto simile a come verrebbe scritto se utilizzasse un semplice input di una sola riga:
90
92
91
93
```javascript{4-6,12-14,26}
92
-
class EssayForm extends React.Component {
94
+
class FormTema extends React.Component {
93
95
constructor(props) {
94
96
super(props);
95
97
this.state = {
96
-
value: 'Please write an essay about your favorite DOM element.'
98
+
value: 'Per favore scrivi un tema riguardo il tuo elemento DOM preferito.'
97
99
};
98
100
99
101
this.handleChange = this.handleChange.bind(this);
@@ -105,15 +107,15 @@ class EssayForm extends React.Component {
105
107
}
106
108
107
109
handleSubmit(event) {
108
-
alert('An essay was submitted: ' + this.state.value);
110
+
alert('Un tema è stato inviato: ' + this.state.value);
@@ -123,25 +125,25 @@ class EssayForm extends React.Component {
123
125
}
124
126
```
125
127
126
-
Notice that`this.state.value`is initialized in the constructor, so that the text area starts off with some text in it.
128
+
Nota come`this.state.value`viene inizializzato nel costruttore, cosìcche la casella di testo è inizializzata con del testo al suo interno.
127
129
128
-
## The select Tag {#the-select-tag}
130
+
## Il Tag Select {#the-select-tag}
129
131
130
-
In HTML, `<select>`creates a drop-down list. For example, this HTML creates a drop-down list of flavors:
132
+
In HTML, `<select>`crea una lista a discesa. Per esempio, questo HTML crea una lista a discesa di gusti:
131
133
132
134
```html
133
135
<select>
134
-
<optionvalue="grapefruit">Grapefruit</option>
135
-
<optionvalue="lime">Lime</option>
136
-
<optionselectedvalue="coconut">Coconut</option>
136
+
<optionvalue="pompelmo">Pompelmo</option>
137
+
<optionvalue="limone">Limone</option>
138
+
<optionselectedvalue="cocco">Cocco</option>
137
139
<optionvalue="mango">Mango</option>
138
140
</select>
139
141
```
140
142
141
-
Note that the Coconut option is initially selected, because of the `selected` attribute. React, instead of using this`selected` attribute, uses a`value`attribute on the root `select` tag. This is more convenient in a controlled component because you only need to update it in one place. For example:
143
+
Nota come l'opzione Cocco venga preselezionata grazie all'attributo `selected`. React, piuttosto che usare l'attributo`selected`, usa l'attributo`value`dell'elemento radice `select`. Ciò facilita le cose in un componente controllato in quanto bisogna aggiornare lo stato in un posto solo. Ad esempio:
142
144
143
145
```javascript{4,10-12,24}
144
-
class FlavorForm extends React.Component {
146
+
class FormGusti extends React.Component {
145
147
constructor(props) {
146
148
super(props);
147
149
this.state = {value: 'coconut'};
@@ -155,19 +157,21 @@ class FlavorForm extends React.Component {
155
157
}
156
158
157
159
handleSubmit(event) {
158
-
alert('Your favorite flavor is: ' + this.state.value);
160
+
alert('Il tuo gusto preferito è: ' + this.state.value);
@@ -178,121 +182,128 @@ class FlavorForm extends React.Component {
178
182
}
179
183
```
180
184
181
-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/JbbEzX?editors=0010)
185
+
**[Prova su CodeSandbox](codesandbox://forms/2.js)**
182
186
183
-
Overall, this makes it so that `<input type="text">`, `<textarea>`, and`<select>`all work very similarly - they all accept a`value`attribute that you can use to implement a controlled component.
187
+
Ricapitolando, ciò fa sì che `<input type="text">`, `<textarea>` e`<select>`funzionino in modo molto simile - tutti accettano un attributo`value`che puoi utilizzare per implementare un componente controllato.
184
188
185
-
> Note
189
+
> **Nota bene**
186
190
>
187
-
> You can pass an array into the `value` attribute, allowing you to select multiple options in a `select` tag:
191
+
> Puoi passare un array nell'attributo `value`, permettendoti di selezionare opzioni multiple in un tag `select`:
188
192
>
189
193
>```js
190
194
><select multiple={true} value={['B', 'C']}>
191
195
>```
192
196
193
-
## The file input Tag {#the-file-input-tag}
197
+
## Il Tag Input File {#the-file-input-tag}
194
198
195
-
In HTML, an`<input type="file">`lets the user choose one or more files from their device storage to be uploaded to a server or manipulated by JavaScript via the [File API](https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications).
199
+
In HTML, un`<input type="file">`permette all'utente di selezionare uno o più file da disco e di inviarli al server o manipolarli in JavaScript mediante le [File API](https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications).
196
200
197
201
```html
198
202
<input type="file"/>
199
203
```
200
204
201
-
Because its value is read-only, it is an**uncontrolled**component in React. It is discussed together with other uncontrolled components [later in the documentation](/docs/uncontrolled-components.html#the-file-input-tag).
205
+
Dato che il suo valore è in sola-lettura, è un componente**non controllato** in React. Riprenderemo il discorso riguardo questo ed altri componenti non controllati [in seguito](/docs/uncontrolled-components.html#the-file-input-tag).
## Gestione di Input Multipli {#handling-multiple-inputs}
204
208
205
-
When you need to handle multiple controlled `input` elements, you can add a`name`attribute to each element and let the handler function choose what to do based on the value of`event.target.name`.
209
+
Quando devi gestire diversi elementi `input`, puoi aggiungere un attributo`name`ad ognuno di essi e far sì che la funzione handler controlli cosa fare in base al valore di`event.target.name`.
const value = target.type === 'checkbox' ? target.checked : target.value;
229
+
const value =
230
+
target.type === 'checkbox'
231
+
? target.checked
232
+
: target.value;
224
233
const name = target.name;
225
234
226
235
this.setState({
227
-
[name]: value
236
+
[name]: value,
228
237
});
229
238
}
230
239
231
240
render() {
232
241
return (
233
242
<form>
234
243
<label>
235
-
Is going:
244
+
Sarà presente:
236
245
<input
237
-
name="isGoing"
246
+
name="presente"
238
247
type="checkbox"
239
-
checked={this.state.isGoing}
240
-
onChange={this.handleInputChange} />
248
+
checked={this.state.presente}
249
+
onChange={this.handleInputChange}
250
+
/>
241
251
</label>
242
252
<br />
243
253
<label>
244
-
Number of guests:
254
+
Numero di ospiti:
245
255
<input
246
-
name="numberOfGuests"
256
+
name="numeroOspiti"
247
257
type="number"
248
-
value={this.state.numberOfGuests}
249
-
onChange={this.handleInputChange} />
258
+
value={this.state.numeroOspiti}
259
+
onChange={this.handleInputChange}
260
+
/>
250
261
</label>
251
262
</form>
252
263
);
253
264
}
254
265
}
255
266
```
256
267
257
-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/wgedvV?editors=0010)
268
+
**[Prova su CodeSandbox](codesandbox://forms/3.js)**
258
269
259
-
Note how we used the ES6 [computed property name](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names)syntax to update the state key corresponding to the given input name:
270
+
Nota come abbiamo utilizzato la sintassi ES6 [_computed property name_ ("nome proprietà calcolato")](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names)per aggiornare la rispettiva chiave nello stato a seconda dell'attributo `name` dell'input:
260
271
261
272
```js{2}
262
273
this.setState({
263
274
[name]: value
264
275
});
265
276
```
266
277
267
-
It is equivalent to this ES5 code:
278
+
Il che in ES5 corrisponde al codice:
268
279
269
280
```js{2}
270
-
var partialState = {};
271
-
partialState[name] = value;
272
-
this.setState(partialState);
281
+
var statoParziale = {};
282
+
statoParziale[name] = value;
283
+
this.setState(statoParziale);
273
284
```
274
285
275
-
Also, since `setState()`automatically [merges a partial state into the current state](/docs/state-and-lifecycle.html#state-updates-are-merged), we only needed to call it with the changed parts.
286
+
Inoltre, dato che `setState()`[unisce uno stato parziale nello stato corrente](/docs/state-and-lifecycle.html#state-updates-are-merged) automaticamente, dobbiamo chiamarla con le sole parti modificate.
276
287
277
-
## Controlled Input Null Value {#controlled-input-null-value}
288
+
## Valore Null in Input Controllati {#controlled-input-null-value}
278
289
279
-
Specifying the value prop on a [controlled component](/docs/forms.html#controlled-components)prevents the user from changing the input unless you desire so. If you've specified a`value`but the input is still editable, you may have accidentally set `value`to`undefined`or`null`.
290
+
Specificare la prop `value` in un [componente controllato](/docs/forms.html#controlled-components)fa sì che l'utente possa cambiare l'input solo quando lo desideri. Se hai specificato un`value`ma l'input è ancora editabile, potresti aver accidentalmente impostato `value`come`undefined`o`null`.
280
291
281
-
The following code demonstrates this. (The input is locked at first but becomes editable after a short delay.)
292
+
Il codice seguente lo dimostra. (L'input è inizialmente bloccato ma diventa editabile dopo un secondo)
## Alternatives to Controlled Components {#alternatives-to-controlled-components}
303
+
## Alternative ai Componenti Controllati {#alternatives-to-controlled-components}
293
304
294
-
It can sometimes be tedious to use controlled components, because you need to write an event handler for every way your data can change and pipe all of the input state through a React component. This can become particularly annoying when you are converting a preexisting codebase to React, or integrating a React application with a non-React library. In these situations, you might want to check out [uncontrolled components](/docs/uncontrolled-components.html), an alternative technique for implementing input forms.
305
+
Utilizzare componenti controllati può sembrare laborioso a volte, soprattutto perché è necessario scrivere un _event handler_ per ogni modo in cui i tuoi dati possono cambiare e perchè si deve collegare lo stato di tutti gli input a quello di un componente React. Il tutto diventa particolarmente noioso quando bisogna convertire progetti preesistenti in React, o integrare un'applicazione React con una libreria non-React. In queste situazioni, si potrebbe ricorrere ai [componenti non controllati](/docs/uncontrolled-components.html), una tecnica alternativa per implementare forms ed i relativi campi di input.
## Soluzioni Chiavi In Mano {#fully-fledged-solutions}
297
308
298
-
If you're looking for a complete solution including validation, keeping track of the visited fields, and handling form submission, [Formik](https://jaredpalmer.com/formik)is one of the popular choices. However, it is built on the same principles of controlled components and managing state — so don't neglect to learn them.
309
+
Se stai cercando una soluzione che include la validazione dei dati, il tener traccia dei campi visitati e la sottomissione del form, [Formik](https://jaredpalmer.com/formik)è una delle scelte popolari. Comunque, si basa sugli stessi principi dei componenti controllati e della gestione dello stato — ecco perché è bene essere familiari con questi concetti.
0 commit comments