Reagire agli eventi
Proprio come gli eventi HTML DOM, React può eseguire azioni basate sugli eventi dell'utente.
React ha gli stessi eventi dell'HTML: clic, modifica, passaggio del mouse ecc.
Aggiunta di eventi
Gli eventi React sono scritti nella sintassi camelCase:
onClick
invece di onclick
.
I gestori di eventi React sono scritti tra parentesi graffe:
onClick={shoot}
invece di
onClick="shoot()"
.
Reagire:
<button onClick={shoot}>Take the Shot!</button>
HTML:
<button onclick="shoot()">Take the Shot!</button>
Esempio:
Metti la shoot
funzione all'interno del
Football
componente:
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
Ottieni la certificazione!
ISCRIVITI A $95
Argomenti di passaggio
Per passare un argomento a un gestore di eventi, utilizzare una funzione freccia.
Esempio:
Invia "Obiettivo!" come parametro della shoot
funzione, utilizzando la funzione freccia:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
Oggetto evento di reazione
I gestori di eventi hanno accesso all'evento React che ha attivato la funzione.
Nel nostro esempio l'evento è l'evento "click".
Esempio:
Freccia Funzione: Invio manuale dell'oggetto evento:
function Football() {
const shoot = (a, b) => {
alert(b.type);
/*
'b' represents the React event that triggered the function,
in this case the 'click' event
*/
}
return (
<button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
Ciò tornerà utile quando esamineremo la Forma in un capitolo successivo.