我正在寻找一种检测点击事件是否在组件外部发生的方法。jQuery最近的()用于查看click事件中的目标是否具有dom元素作为其父元素之一。如果存在匹配项,则单击事件属于子项之一,因此不被视为在组件之外。
因此,在我的组件中,我想将单击处理程序附加到窗口。当处理程序触发时,我需要将目标与组件的dom子代进行比较。
click事件包含“path”之类的属性,该属性似乎包含事件经过的dom路径。我不确定要比较什么或如何最好地遍历它,并且我认为有人必须已经将其放在聪明的实用程序函数中了……不?
以下解决方案使用ES6,并遵循最佳实践进行绑定以及通过一种方法设置ref。
Class Implementation::
import React, { Component } from 'react'; /** * Component that alerts if you click outside of it */ export default class OutsideAlerter extends Component { constructor(props) { super(props); this.setWrapperRef = this.setWrapperRef.bind(this); this.handleClickOutside = this.handleClickOutside.bind(this); } componentDidMount() { document.addEventListener('mousedown', this.handleClickOutside); } componentWillUnmount() { document.removeEventListener('mousedown', this.handleClickOutside); } /** * Set the wrapper ref */ setWrapperRef(node) { this.wrapperRef = node; } /** * Alert if clicked on outside of element */ handleClickOutside(event) { if (this.wrapperRef && !this.wrapperRef.contains(event.target)) { alert('You clicked outside of me!'); } } render() { return <div ref={this.setWrapperRef}>{this.props.children}</div>; } } OutsideAlerter.propTypes = { children: PropTypes.element.isRequired, };
Hooks Implementation:
import React, { useRef, useEffect } from "react"; /** * Hook that alerts clicks outside of the passed ref */ function useOutsideAlerter(ref) { useEffect(() => { /** * Alert if clicked on outside of element */ function handleClickOutside(event) { if (ref.current && !ref.current.contains(event.target)) { alert("You clicked outside of me!"); } } // Bind the event listener document.addEventListener("mousedown", handleClickOutside); return () => { // Unbind the event listener on clean up document.removeEventListener("mousedown", handleClickOutside); }; }, [ref]); } /** * Component that alerts if you click outside of it */ export default function OutsideAlerter(props) { const wrapperRef = useRef(null); useOutsideAlerter(wrapperRef); return <div ref={wrapperRef}>{props.children}</div>; }