LoginSignup
1
0

More than 1 year has passed since last update.

SyntheticEventとは

Last updated at Posted at 2023-01-10

SyntheicEventとは

イベントは、ブラウザ毎に動作が異なるケースがありますが
Reactでは、Reactを使用するユーザーに一貫した経験を提供するためにSyntheicEventオブジェクトを 使用します。 SyntheicEventとブラウザののイベントはほぼ一緒ですが、全く同じものではありません。

SyntheicEventの特徴1

import React from 'react'

export default function Event() {
    const handleButtonClick = (e) => {
        console.log('handleButtonClick');
    }
    const handleMouseLeave = (e) => {
        console.log('handleMouseLeave');
        console.dir(e);
    }
    const handleClickCapture = () => {
        console.log('handleClickCapture');
    }
    const handleClickCapture2 = () => {
        console.log('handleClickCapture2');
    }
    const handleClickBubble = () => {
        console.log('handleClickBubble');
    }

    return (
        <div onClickCapture={handleClickCapture}>
            <div onClickCapture={handleClickCapture2} onClick={handleClickBubble}>
                <button onClick={handleButtonClick} onMouseLeave={handleMouseLeave}>Button</button>
            </div>
        </div>
    )
}

image.png
ここでボタンからマウスを離すと、SyntheticEventを受取ます。
image.png

上記で、SyntheicEventとブラウザのイベントは少し違いがあると話しましたが、ここでその理由が分かります。
SyntheicEventのnativeEvent中を見ると、実際に起こるイベントはmouseoutであることが分かります。
image.png

SyntheicEventの特徴2

javascriptではformでreturn falseをするとdefault eventが制御されますが、 Reactではreturn falseの機能を提供せず、その代わりにevent.preventDefault()を提供しています。 formでsubmitをするとdefault eventとしてページ更新が起こりますが、preventDefault()を指定することでページ更新が起こらないようになります。
import React from 'react'

export default function Event() {
    const handleSubmit = (event) => {
        event.preventDefault();  // do prevent default event
        console.dir(event.target); 
    };

    return (
        <form onSubmit={handleSubmit}>
            <input type="submit" defaultValue="Submit" />
        </form>
    )
}

Captureとbubble

Capture:親から子まで下りながら誰が呼ばれたか、ターゲットを探す行為。
     例えば、ボタンが押されたらボタンを囲んでいるDOMの一番最初は親が呼ばれます。
Bubble:Captureが終了した後(ターゲット特定済みの状況)ターゲットの親のイベントをチェック
ReactではcaptureをonClickCaptureとして提供。

「SyntheicEventの特徴1」のコードからReactではどのようにCaptureとBubbleが動くか分かります。

image.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0