() translation by (you can also view the original English article)
In questo tutorial, imparerete forms ed eventi in React. Inizieremo creando una semplice applicazione React e aggiungeremo un form e alcuni elementi. Poi vedremo come aggiungere eventi agli elementi del form.
Se avete appena iniziato a usare React, vi consigliamo di leggere il tutorial introduttivo.
Introduzione
Iniziamo impostando la nostra applicazione React. Create una cartella di progetto denominata ReactFormApp
. Dentro ReactFormApp
create un file chiamato index.html
e aggiungete il seguente codice HTML:
1 |
<html>
|
2 |
|
3 |
<head>
|
4 |
<title>TutsPlus - React Forms & Events</title> |
5 |
</head>
|
6 |
|
7 |
<body>
|
8 |
<div id="app"></div> |
9 |
<script src="bundle.js"></script> |
10 |
</body>
|
11 |
|
12 |
</html>
|
Inizializzate il progetto usando Node Package Manager (npm).
1 |
npm init |
Inserite i dettagli richiesti e dovreste avere il file package.json
dentro la cartella ReactFormApp
.
1 |
{
|
2 |
"name": "reactformapp", |
3 |
"version": "1.0.0", |
4 |
"description": "", |
5 |
"main": "index.js", |
6 |
"scripts": { |
7 |
"test": "echo \"Error: no test specified\" && exit 1" |
8 |
},
|
9 |
"author": "", |
10 |
"license": "ISC" |
11 |
}
|
Installate le dipendenze react
e react-dom
usando npm.
1 |
npm install react react-dom --save |
Installate il package babel richiesto usando npm e salvatelo nel file package.json
.
1 |
npm install --save-dev webpack webpack-dev-server babel-core babel-loader babel-preset-react babel-preset-es2015 |
I packages babel
sono richiesti per trasformare il codice JSX in JavaScript.
Create un file di configurazione webpack per gestire le configurazioni webpack. Create un file chiamato webpack.config.js
e aggiungete le seguenti configurazioni:
1 |
module.exports = { |
2 |
entry: './app.js', |
3 |
|
4 |
output: { |
5 |
filename: 'bundle.js', |
6 |
},
|
7 |
|
8 |
module: { |
9 |
loaders: [ |
10 |
{ exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' } |
11 |
]
|
12 |
}
|
13 |
}
|
app.js
è il file in cui risiederà il nostro codice React. Create un file chiamato app.js
dentro la cartella ReactFormApp
. Importate le librerie react richieste in app.js.
Create un componente denominato App
avente un div con del testo. Eseguite il rendering del componente usando il metodo render. Ecco come apparirà il file app.js
:
1 |
import React from 'react' |
2 |
import { render } from 'react-dom' |
3 |
|
4 |
var App = React.createClass({ |
5 |
render:function(){ |
6 |
return( |
7 |
<div> |
8 |
TutsPlus - Welcome to React Form App |
9 |
</div> |
10 |
);
|
11 |
}
|
12 |
});
|
13 |
|
14 |
render(( |
15 |
<App /> |
16 |
),document.getElementById('app')) |
Salvate le modifiche e riavviate il server di sviluppo webpack.
1 |
webpack-dev-server |
Una volta che il server è stato riavviato, dovreste essere in grado di vedere l'applicazione React all'indirizzo http://localhost:8080/.



Create un Form React
Abbiamo una semplice applicazione React impostata e funzionante. Andiamo al passaggio successivo e proviamo a creare un componente form usando codice JSX in app.js
.
Create un componente chiamato FormComp
all'interno di app.js
.
1 |
var FormComp = React.createClass({ |
2 |
render:function(){ |
3 |
return( |
4 |
);
|
5 |
}
|
6 |
})
|
All'interno della funzione render per FormComp definiremo il codice HTML per creare un form. Inseriremo un paio di labels, boxes di input e un pulsante da cliccare. Ecco come apparirà:
1 |
var FormComp = React.createClass({ |
2 |
render:function(){ |
3 |
return( |
4 |
<div> |
5 |
|
6 |
<h2>TutsPlus - React Form Tutorial</h2> |
7 |
<hr /> |
8 |
|
9 |
<label>First Name: </label> |
10 |
<input type="text" /> |
11 |
<br /> |
12 |
|
13 |
<label>Last Name: </label> |
14 |
<input type="text" /> |
15 |
<br /> |
16 |
|
17 |
<input type="button" value="Submit" /> |
18 |
|
19 |
<hr /> |
20 |
</div> |
21 |
);
|
22 |
}
|
23 |
})
|
Eseguite il rendering del componente form FormComp
per visualizzare il form all'interno di index.html
.
1 |
render(( |
2 |
<FormComp /> |
3 |
),document.getElementById('app')) |
Salvate le modifiche, riavviate il server webpack e dovreste ora vedere il form.



Aggiungere Eventi al Form
Il nostro form React è in buona forma. Per farlo interagire dobbiamo aggiungere eventi al form.
Cominceremo aggiungendo variabili di stato su ognuno dei boxes di input così che potremo leggerne i valori. Impostiamo le variabili di stato per i box di inserimento testo nome e cognome.
1 |
<input type="text" value = {this.state.fName} /> |
2 |
<input type="text" value = {this.state.lName} /> |
Siate sicuri di impostare lo stato iniziale per le variabili soprastanti. Definite la funzione getInitialState
dentro il componente FormComp
e inizializzate entrambe le variabili.
1 |
getInitialState: function () { |
2 |
return {lName: '',fName:''}; |
3 |
},
|
Abbiamo bisogno di gestire l'evento on-change dei boxes di input e assegnare le variabili di stato quando il valore nei boxes di testo cambia. Definite quindi un evento onChange
nei boxes di input.
1 |
<input type="text" value = {this.state.fName} onChange={this.handleFNameChange} /> |
2 |
<input type="text" value = {this.state.lName} onChange={this.handleLNameChange} /> |
Definite le funzioni onChange
dentro FormComp
e impostate le variabili di stato.
1 |
handleFNameChange:function(event){ |
2 |
this.setState({fName: event.target.value}); |
3 |
},
|
4 |
|
5 |
handleLNameChange:function(event){ |
6 |
this.setState({lName: event.target.value}); |
7 |
}
|
Proviamo a eseguire il rendering delle variabili di stato, usandole. Dentro l'HTML di FormComp
aggiungete il seguente elemento che esegue il rendering delle variabili di stato.
1 |
<h3>Your full name is </h3> {this.state.fName} {this.state.lName} |
Salvate le modifiche e riavviate il server webpack. Cercate di inserire del testo dentro i boxes nome e cognome, e dovreste vedere i risultati mentre digitate.



Successivamente, aggiungiamo un evento on-click al pulsante submit che troviamo nel nostro form.
1 |
<input type="button" onClick={this.handleClick} value="Submit" /> |
Definiamo la funzione handleClick
dentro il componente FormComp
. Cliccando sul pulsante submit concateneremo sia nome che cognome e visualizzeremo il nome completo nel form. Di seguito la funzione handleClick
:
1 |
handleClick:function(){ |
2 |
var fullName = this.state.fName + ' ' + this.state.lName; |
3 |
this.setState({Name:fullName}); |
4 |
},
|
Inoltre, inizializziamo la variabile Name
nella funzione getInitialState
.
1 |
getInitialState: function () { |
2 |
return {lName: '',fName:'',Name:''}; |
3 |
}
|
Visualizziamo il nome completo concatenato nel form HTML.
1 |
<h3>Your full name is </h3> {this.state.Name} |
Ecco come apparirà il componente finale FormComp
:
1 |
var FormComp = React.createClass({ |
2 |
|
3 |
|
4 |
getInitialState: function () { |
5 |
return {lName: '',fName:'',Name:''}; |
6 |
},
|
7 |
|
8 |
handleFNameChange:function(event){ |
9 |
this.setState({fName: event.target.value}); |
10 |
},
|
11 |
|
12 |
handleLNameChange:function(event){ |
13 |
this.setState({lName: event.target.value}); |
14 |
},
|
15 |
|
16 |
handleClick:function(){ |
17 |
var fullName = this.state.fName + ' ' + this.state.lName; |
18 |
this.setState({Name:fullName}); |
19 |
},
|
20 |
|
21 |
render:function(){ |
22 |
return( |
23 |
<div> |
24 |
<h2>TutsPlus - React Form Tutorial</h2> |
25 |
<hr /> |
26 |
|
27 |
<label>First Name: </label> |
28 |
<input type="text" value = {this.state.fName} onChange={this.handleFNameChange} /> |
29 |
<br /> |
30 |
|
31 |
<label>Last Name: </label> |
32 |
<input type="text" value = {this.state.lName} onChange={this.handleLNameChange} /> |
33 |
<br /> |
34 |
|
35 |
<input type="button" onClick={this.handleClick} value="Submit" /> |
36 |
|
37 |
<hr /> |
38 |
|
39 |
<h3>Your full name is </h3> {this.state.Name} |
40 |
</div> |
41 |
);
|
42 |
}
|
43 |
})
|
Salvate i cambiamenti soprastanti e riavviate il server di sviluppo. Inserite entrambi i nomi e cliccate sul pulsante submit, dovrebbe essere visualizzato il nome completo.
Riassumendo
In questo tutorial avete imparato come iniziare a realizzare applicazioni React e a capire i concetti base sul gestire forms ed eventi in un'applicazione web React. Spero che questo tutorial sia stato utile per introdurvi alla realizzazione di applicazioni basate su React.
Il codice sorgente di questo tutorial è disponibile su GitHub.
Fateci sapere le vostre considerazioni, suggerimenti o qualsiasi correzione nei commenti sottostanti. Continuate a controllare questo spazio per ulteriori tutorials React.