以下解決方案使用ES6并遵循綁定的最佳實(shí)踐以及通過方法設(shè)置ref。
要看到它的實(shí)際效果:
課程實(shí)施:
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,};
鉤子實(shí)施:
import React, { useRef, useEffect } from "react";/**
* Hook that alerts clicks outside of the passed ref
*/function useOutsideAlerter(ref) {
/**
* Alert if clicked on outside of element
*/
function handleClickOutside(event) {
if (ref.current && !ref.current.contains(event.target)) {
alert("You clicked outside of me!");
}
}
useEffect(() => {
// Bind the event listener
document.addEventListener("mousedown", handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
});}/**
* 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>;}