react如何监听document
监听 document 事件的方法
在 React 中监听 document 对象的事件(如点击、滚动、按键等)需通过原生 DOM API 实现,并结合 React 的生命周期或 Hooks 管理监听器的绑定与卸载。
类组件实现方式
在 componentDidMount 中绑定事件,在 componentWillUnmount中移除监听:
import React from 'react';
class DocumentListener extends React.Component {
handleKeyPress = (e) => {
console.log('Key pressed:', e.key);
};
componentDidMount() {
document.addEventListener('keydown', this.handleKeyPress);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeyPress);
}
render() {
return <div>Check console for key presses</div>;
}
}
函数组件实现方式(Hooks)
使用 useEffect 处理副作用,返回清理函数以移除监听:
import React, { useEffect } from 'react';
function DocumentListener() {
const handleClick = (e) => {
console.log('Clicked at:', e.clientX, e.clientY);
};
useEffect(() => {
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
};
}, []); // 空依赖数组确保只运行一次
return <div>Click anywhere on the page</div>;
}
注意事项
-
依赖数组:若事件处理函数依赖组件状态或 props,需将其添加到
useEffect的依赖数组中,并确保在更新时重新绑定。useEffect(() => { document.addEventListener('click', handleClick); return () => document.removeEventListener('click', handleClick); }, [handleClick]); // 依赖 handleClick 的变化 -
性能优化:对于高频事件(如
scroll或mousemove),建议使用节流(throttle)或防抖(debounce)减少处理频率。 -
事件类型:支持所有标准 DOM 事件(如
keydown、resize、visibilitychange等)。
示例:监听页面滚动
function ScrollTracker() {
useEffect(() => {
const handleScroll = () => {
console.log('Scroll position:', window.scrollY);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return <div>Scroll and check console</div>;
}
通过上述方法,可以安全地在 React 中监听 document 或 window 的全局事件。







