以下解决方案使用ES6,并遵循最佳实践进行绑定以及通过一种方法设置ref。
Class Implementation::
import React, { Component } from 'react';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); } setWrapperRef(node) { this.wrapperRef = node; } 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";function useOutsidealerter(ref) { useEffect(() => { 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]);}export default function Outsidealerter(props) { const wrapperRef = useRef(null); useOutsidealerter(wrapperRef); return <div ref={wrapperRef}>{props.children}</div>;}


