Tepki Olayları


Tıpkı HTML DOM olayları gibi, React de kullanıcı olaylarına göre eylemler gerçekleştirebilir.

React, HTML ile aynı olaylara sahiptir: tıklama, değiştirme, fareyle üzerine gelme vb.


Etkinlik Ekleme

React olayları camelCase sözdiziminde yazılır:

onClick yerine onclick.

React olay işleyicileri küme parantezleri içinde yazılmıştır:

onClick={shoot}  yerine onClick="shoot()".

Tepki:

<button onClick={shoot}>Take the Shot!</button>

HTML:

<button onclick="shoot()">Take the Shot!</button>

Örnek:

shootİşlevi Footballbileşenin içine koyun :

function Football() {
  const shoot = () => {
    alert("Great Shot!");
  }

  return (
    <button onClick={shoot}>Take the shot!</button>
  );
}

ReactDOM.render(<Football />, document.getElementById('root'));


w3schools CERTIFIED . 2022

Sertikalı olmak!

React modüllerini tamamlayın, alıştırmaları yapın, sınava girin ve w3schools sertifikalı olun!

95 $ KAYIT

Argümanları Geçmek

Bir olay işleyicisine bir argüman iletmek için bir ok işlevi kullanın.

Örnek:

"Gol!" Gönder shoot ok işlevini kullanarak işleve parametre olarak :

function Football() {
  const shoot = (a) => {
    alert(a);
  }

  return (
    <button onClick={() => shoot("Goal!")}>Take the shot!</button>
  );
}

ReactDOM.render(<Football />, document.getElementById('root'));


React Olay Nesnesi

Olay işleyicileri, işlevi tetikleyen React olayına erişebilir.

Örneğimizde olay "tıklama" olayıdır.

Örnek:

Ok İşlevi: Olay nesnesini manuel olarak gönderme:

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'));

Bu, daha sonraki bir bölümde Form'a baktığımızda kullanışlı olacaktır .


Egzersizlerle Kendinizi Test Edin

Egzersiz yapmak:

Bir tıklama olay işleyicisi eklemek için bu ifadeyi tamamlayın.

<button ={clicked()}>Click Me!</button>