LoginSignup
1
1

特定の子要素のみにクリックイベントを割り当てたいときはe.stopPropagation();を使用する

Posted at

はじめに

React×TypeScriptでアプリを作成しています。
「特定の要素だけをクリックしたい!」と思うことがあり、初めてe.stopPropagation();を使用したので概要を軽くまとめます。

e.stopPropagation();とは

クリックイベントのパブリング(特定のイベントが親要素に伝播する現状)のを防ぐために使用されます。
つまり、特定のイベントを特定の要素のみに割り当てたい時に使用します。


イベントパブリングとは

JavaScriptのDOMツリー内で発生したイベントが、発生した要素から親要素に向かって順番に伝播していく現象です。

仮に子要素のボタンをクリックした場合、クリックイベントは下記の順番で発生します。

jsx
<div id="parent">
  <button id="child">Click me</button>
</div>

1.子要素(ボタン)
2.親要素(div)
3.(存在する場合)さらに上位の親要素へ

1→2への伝播を防ぐ場合にe.stopPropagation();を使用します。

具体例

tsx
import React from 'react';

const App = () => {
  const handleParentClick = () => {
    console.log("親要素がクリックされました");
  };

  const handleChildClick = (e) => {
    e.stopPropagation(); // 親要素へのバブリングを停止
    console.log("子要素がクリックされました");
  };

  return (
    <div onClick={handleParentClick} style={{ padding: '20px', border: '1px solid red' }}>
      親要素
      <button onClick={handleChildClick}>子要素のボタン</button>
    </div>
  );
};

export default App;

必要ないケース

・親要素にクリックイベントが設定されていない場合
・子要素のクリックイベントが親要素のイベントに影響を与えない場合

参考

1
1
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
1