Eventos
Al igual que los eventos DOM HTML, 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
Los eventos de React se escriben en sintaxis camelCase:
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>Ejemplo:
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 />);gfh
Pasando argumentos
Para pasar un argumento a un controlador de eventos, utilice una función de flecha.
Ejemplo:
Envía "¡Gol!" como parámetro a 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 />);Objeto de evento de React
Los controladores de eventos tienen acceso al evento React que activó la función.
En nuestro ejemplo, el evento es el evento "clic".
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 />);Esto será útil cuando analicemos el Formulario en un capítulo posterior.
fdg
Comentarios
Publicar un comentario