Reactイベント


HTML DOMイベントと同様に、Reactはユーザーイベントに基づいてアクションを実行できます。

ReactにはHTMLと同じイベントがあります:クリック、変更、マウスオーバーなど。


イベントの追加

ReactイベントはcamelCase構文で記述されています。

onClick の代わりにonclick

Reactイベントハンドラーは中括弧内に記述されています。

onClick={shoot}  の代わりに onClick="shoot()"

反応:

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

HTML:

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

例:

関数をコンポーネントshoot内に 配置します。Football

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

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

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


w3schools CERTIFIED . 2022

認定を受けましょう!

Reactモジュールを完了し、演習を行い、試験を受けて、w3schools認定を取得してください!!

95ドル登録

引数の受け渡し

イベントハンドラに引数を渡すには、矢印関数を使用します。

例:

「ゴール!」を送る shoot 矢印関数を使用して、関数のパラメーターとして:

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

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

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


Reactイベントオブジェクト

イベントハンドラーは、関数をトリガーしたReactイベントにアクセスできます。

この例では、イベントは「クリック」イベントです。

例:

矢印関数:イベントオブジェクトを手動で送信します。

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

これは、後の章でフォームを見るときに役立ちます。


エクササイズで自分をテストする

エクササイズ:

このステートメントを完成させて、クリックイベントハンドラーを含めます。

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