Reaccionar eventos
Al igual que los eventos HTML DOM, React puede realizar acciones en función de los eventos del usuario.
React tiene los mismos eventos que HTML: hacer clic, cambiar, pasar el mouse, etc.
Adición de eventos
Los eventos React están escritos en sintaxis camelCase:
onClick
en lugar onclick
de
Los controladores de eventos React se escriben entre llaves:
onClick={shoot}
en lugar
onClick="shoot()"
de
Reaccionar:
<button onClick={shoot}>Take the Shot!</button>
HTML:
<button onclick="shoot()">Take the Shot!</button>
Ejemplo:
Ponga la shoot
función dentro del
Football
componente:
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
¡Obtener la certificación!
$95 INSCRÍBETE
pasar argumentos
Para pasar un argumento a un controlador de eventos, use una función de flecha.
Ejemplo:
Enviar "¡Gol!" como parámetro a la shoot
función, usando la función flecha:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
Reaccionar objeto de evento
Los controladores de eventos tienen acceso al evento React que activó la función.
En nuestro ejemplo, el evento es el evento "clic".
Ejemplo:
Función de flecha: enviar el 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'));
Esto será útil cuando veamos Forma en un capítulo posterior.