Acara Reaksi
Sama seperti event HTML DOM, React dapat melakukan tindakan berdasarkan event pengguna.
React memiliki event yang sama dengan HTML: click, change, mouseover, dll.
Menambahkan Acara
Peristiwa React ditulis dalam sintaks camelCase:
onClick
bukannya onclick
.
React event handler ditulis di dalam kurung kurawal:
onClick={shoot}
bukannya
onClick="shoot()"
.
Reaksi:
<button onClick={shoot}>Take the Shot!</button>
HTML:
<button onclick="shoot()">Take the Shot!</button>
Contoh:
Letakkan shoot
fungsi di dalam
Football
komponen:
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
Dapatkan Sertifikasi!
$95 DAFTAR
Melewati Argumen
Untuk meneruskan argumen ke event handler, gunakan fungsi panah.
Contoh:
Kirim "Gol!" sebagai parameter ke shoot
fungsi, menggunakan fungsi panah:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
Objek Acara Bereaksi
Penangan acara memiliki akses ke acara React yang memicu fungsi.
Dalam contoh kami, acara tersebut adalah acara "klik".
Contoh:
Fungsi Panah: Mengirim objek acara secara manual:
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'));
Ini akan berguna ketika kita melihat Formulir di bab selanjutnya.