Detect click outside React component

后端 未结 30 1524
日久生厌
日久生厌 2020-11-22 13:54

I\'m looking for a way to detect if a click event happened outside of a component, as described in this article. jQuery closest() is used to see if the target from a click e

30条回答
  •  感情败类
    2020-11-22 14:27

    Alternatively to .contains, you can use the .closest method. When you want to check if a click was outside of the element with id="apple" then i can use:

    const isOutside = !e.target.closest("#apple");
    

    This checks if any element in the tree above the clicked one has an id of "apple". We have to negate the result!

提交回复
热议问题