Eventos de reação
Assim como os eventos HTML DOM, o React pode realizar ações baseadas em eventos do usuário.
React tem os mesmos eventos que HTML: click, change, mouseover etc.
Adicionando eventos
Os eventos React são escritos na sintaxe camelCase:
onClick
em vez de onclick
.
Os manipuladores de eventos React são escritos dentro de chaves:
onClick={shoot}
em vez de
onClick="shoot()"
.
Reagir:
<button onClick={shoot}>Take the Shot!</button>
HTML:
<button onclick="shoot()">Take the Shot!</button>
Exemplo:
Coloque a shoot
função dentro do
Football
componente:
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
Obter certificação!
$ 95 INSCRIÇÃO
Argumentos de passagem
Para passar um argumento para um manipulador de eventos, use uma função de seta.
Exemplo:
Envie "Gol!" como parâmetro para a shoot
função, usando a função de seta:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
Objeto de evento de reação
Os manipuladores de eventos têm acesso ao evento React que acionou a função.
Em nosso exemplo, o evento é o evento "click".
Exemplo:
Função de seta: Enviando o objeto de evento manualmente:
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'));
Isso será útil quando examinarmos Form em um capítulo posterior.