Detect click outside React component

后端 未结 30 1529
日久生厌
日久生厌 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:15

    My biggest concern with all of the other answers is having to filter click events from the root/parent down. I found the easiest way was to simply set a sibling element with position: fixed, a z-index 1 behind the dropdown and handle the click event on the fixed element inside the same component. Keeps everything centralized to a given component.

    Example code

    #HTML
    
    ...content
    this.setState({open: false})}>
    #SASS .dropdown { display: none; position: absolute; top: 0px; left: 0px; z-index: 100; &.open { display: block; } } .outer-handler { position: fixed; top: 0; left: 0; right: 0; bottom: 0; opacity: 0; z-index: 99; display: none; &.open { display: block; } }

提交回复
热议问题