React Events
Reaccionar eventos
Al igual que los eventos HTML DOM, React puede realizar acciones basadas en eventos del usuario.React tiene los mismos eventos que HTML: hacer clic, cambiar, pasar el mouse, etc.Agregar eventos
onClick en lugar de onclick.
Los controladores de eventos de React están escritos entre llaves:
onClick={shoot} en lugar de onclick="shoot()".
React:
<button onClick={shoot}>Take the Shot!</button>
Html:
<button onclick="shoot()">Take the Shot!</button>
Coloque la shootfunción dentro del Footballcomponente:
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
Pasar argumentos
Ejemplo:
Enviar "¡Gol!" como parámetro de la shoot función, usando la función de flecha:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
Reaccionar objeto de evento
Los controladores de eventos tienen acceso al evento de 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>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
Comentarios
Publicar un comentario