Skip to content

Translation for the page 'Basics -> Forms' #117

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Mar 1, 2019
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
.cache
.DS_STORE
.idea
.vscode
node_modules
public
yarn-error.log
1 change: 1 addition & 0 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Glossary of the translations of technical and React-specific terms.
- tag
- lifecycle
- callback
- form/forms


# Common Translations
Expand Down
163 changes: 87 additions & 76 deletions content/docs/forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,30 +9,30 @@ redirect_from:
- "docs/forms-zh-CN.html"
---

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:
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:

```html
<form>
<label>
Name:
<input type="text" name="name" />
Nome:
<input type="text" name="nome" />
</label>
<input type="submit" value="Submit" />
</form>
```

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".
La sottomissione di questo form porta l'utente in una nuova pagina, questo è il comportamento di _default_ (di fabbrica). In React, se vuoi avere lo stesso comportamento, funziona. Ad ogni modo, potrebbe essere più conveniente avere una funzione JavaScript che gestisce la sottomissione 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".

## Controlled Components {#controlled-components}
## Componenti Controllati {#controlled-components}

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).
In HTML, gli eleenti 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 eviene poi aggiornato solo mediante [`setState()`](/docs/react-component.html#setstate).

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".
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. Un elemento di input in un form, il quale valore è controllato da React viene così chiamato "componente controllato".

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:
Ad esempio, se vogliiamo far si che l'esempio precedente registri il nome inserito, possiamo riscrivere il form sotto forma di componente controllato:

```javascript{4,10-12,24}
class NameForm extends React.Component {
class FormNome extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
Expand All @@ -46,15 +46,15 @@ class NameForm extends React.Component {
}

handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
alert('E\' stato inserito un nome: ' + this.state.value);
event.preventDefault();
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
Nome:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
Expand All @@ -64,36 +64,38 @@ class NameForm extends React.Component {
}
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/VmmPgp?editors=0010)
**[Prova su CodeSandbox](codesandbox://forms/1.js)**

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.
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 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.

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:
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ì:

```javascript{2}
handleChange(event) {
this.setState({value: event.target.value.toUpperCase()});
}
```

## The textarea Tag {#the-textarea-tag}
## Il Tag Textarea {#the-textarea-tag}

In HTML, a `<textarea>` element defines its text by its children:
In HTML, l'elemento `<textarea>` definisce il testo in esso contenuto con i suoi elementi figli:

```html
<textarea>
Hello there, this is some text in a text area
Nel mezzo del cammin di nostra vita
mi ritrovai per una selva oscura
ché la diritta via era smarrita.
</textarea>
```

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:
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:

```javascript{4-6,12-14,26}
class EssayForm extends React.Component {
class FormTema extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'Please write an essay about your favorite DOM element.'
value: 'Per favore scrivi un tema riguardo il tuo elemento DOM preferito.'
};

this.handleChange = this.handleChange.bind(this);
Expand All @@ -105,15 +107,15 @@ class EssayForm extends React.Component {
}

handleSubmit(event) {
alert('An essay was submitted: ' + this.state.value);
alert('Un tema è stato sottomesso: ' + this.state.value);
event.preventDefault();
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Essay:
Tema:
<textarea value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
Expand All @@ -123,25 +125,25 @@ class EssayForm extends React.Component {
}
```

Notice that `this.state.value` is initialized in the constructor, so that the text area starts off with some text in it.
Nota come `this.state.value` viene inizializzato nel costruttore, cosìcche la casella di testo è inizializzata con del testo al suo interno.

## The select Tag {#the-select-tag}
## Il Tag Select {#the-select-tag}

In HTML, `<select>` creates a drop-down list. For example, this HTML creates a drop-down list of flavors:
In HTML, `<select>` crea una lista a discesa. Per esempio, questo HTML crea una lista a discesa di gusti:

```html
<select>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option selected value="coconut">Coconut</option>
<option value="pompelmo">Pompelmo</option>
<option value="limone">Limone</option>
<option selected value="cocco">Cocco</option>
<option value="mango">Mango</option>
</select>
```

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:
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:

```javascript{4,10-12,24}
class FlavorForm extends React.Component {
class FormGusti extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
Expand All @@ -155,19 +157,21 @@ class FlavorForm extends React.Component {
}

handleSubmit(event) {
alert('Your favorite flavor is: ' + this.state.value);
alert('Il tuo gusto preferito è: ' + this.state.value);
event.preventDefault();
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
Seleziona il tuo gusto preferito:
<select
value={this.state.value}
onChange={this.handleChange}>
<option value="pompelmo">Pompelmo</option>
<option value="limone">Limone</option>
<option value="cocco">Cocco</option>
<option value="mango">Mango</option>
</select>
</label>
Expand All @@ -178,121 +182,128 @@ class FlavorForm extends React.Component {
}
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/JbbEzX?editors=0010)
**[Prova su CodeSandbox](codesandbox://forms/2.js)**

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.
Ricapitolando, ciò fa si 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.

> Note
> **Nota bene**
>
> You can pass an array into the `value` attribute, allowing you to select multiple options in a `select` tag:
> Puoi passare un array nell'attributo `value`, permettendoti di selezionare opzioni multiple in un tag `select`:
>
>```js
><select multiple={true} value={['B', 'C']}>
>```

## The file input Tag {#the-file-input-tag}
## Il Tag Input File {#the-file-input-tag}

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).
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).

```html
<input type="file" />
```

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).
Dato che il suo valore è 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).

## Handling Multiple Inputs {#handling-multiple-inputs}
## Gestione di Input Multipli {#handling-multiple-inputs}

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`.
Quando devi gestire diversi elementi `input`, puoi aggiungere un attributo `name` ad ognuno di essi e far si che la funzione handler controlli cosa fare in base al valore di `event.target.name`.

For example:
Ad esempio:

```javascript{15,18,28,37}
class Reservation extends React.Component {
```javascript{20,23,33,43}
class Prenotazione extends React.Component {
constructor(props) {
super(props);
this.state = {
isGoing: true,
numberOfGuests: 2
presente: true,
numeroOspiti: 2,
};

this.handleInputChange = this.handleInputChange.bind(this);
this.handleInputChange = this.handleInputChange.bind(
this
);
}

handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const value =
target.type === 'checkbox'
? target.checked
: target.value;
const name = target.name;

this.setState({
[name]: value
[name]: value,
});
}

render() {
return (
<form>
<label>
Is going:
Sarà presente:
<input
name="isGoing"
name="presente"
type="checkbox"
checked={this.state.isGoing}
onChange={this.handleInputChange} />
checked={this.state.presente}
onChange={this.handleInputChange}
/>
</label>
<br />
<label>
Number of guests:
Numero di ospiti:
<input
name="numberOfGuests"
name="numeroOspiti"
type="number"
value={this.state.numberOfGuests}
onChange={this.handleInputChange} />
value={this.state.numeroOspiti}
onChange={this.handleInputChange}
/>
</label>
</form>
);
}
}
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/wgedvV?editors=0010)
**[Prova su CodeSandbox](codesandbox://forms/3.js)**

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:
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:

```js{2}
this.setState({
[name]: value
});
```

It is equivalent to this ES5 code:
Il che in ES5 corrisponde al codice:

```js{2}
var partialState = {};
partialState[name] = value;
this.setState(partialState);
var statoParziale = {};
statoParziale[name] = value;
this.setState(statoParziale);
```

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.
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.

## Controlled Input Null Value {#controlled-input-null-value}
## Valore Null in Input Controllati {#controlled-input-null-value}

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`.
Specificando la prop `value` in un [componente controllato](/docs/forms.html#controlled-components) può far si che l'utente non possa cambiare l'input, a meno che tu lo desideri. Se hai specificato un `value` ma l'input è ancora editabile, potresti aver accidentalmente impostato `value` come `undefined` o `null`.

The following code demonstrates this. (The input is locked at first but becomes editable after a short delay.)
Il codice seguente lo dimostra. (L'input è inizialmente bloccato ma diventa editabile dopo un secondo)

```javascript
ReactDOM.render(<input value="hi" />, mountNode);
ReactDOM.render(<input value="ciao" />, mountNode);

setTimeout(function() {
ReactDOM.render(<input value={null} />, mountNode);
}, 1000);

```

## Alternatives to Controlled Components {#alternatives-to-controlled-components}
## Alternative ai Componenti Controllati {#alternatives-to-controlled-components}

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.
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.

## Fully-Fledged Solutions {#fully-fledged-solutions}
## Soluzioni Chiavi In Mano {#fully-fledged-solutions}

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 stateso don't neglect to learn them.
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 statoecco perché è bene essere familiari con questi concetti.
Loading