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'));
引数の受け渡し
イベントハンドラに引数を渡すには、矢印関数を使用します。
例:
「ゴール!」を送る 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'));
これは、後の章でフォームを見るときに役立ちます。