Detect click outside React component

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

    For those who need absolute positioning, a simple option I opted for is to add a wrapper component that is styled to cover the whole page with a transparent background. Then you can add an onClick on this element to close your inside component.

    handleOutsideClick()} >

    As it is right now if you add a click handler on content, the event will also be propagated to the upper div and therefore trigger the handlerOutsideClick. If this is not your desired behavior, simply stop the event progation on your handler.

     {
                                              e.stopPropagation();
                                              desiredFunctionCall();
                                            }}/>
    

    `

提交回复
热议问题