react如何监听滚动高度
监听滚动高度的基本方法
在React中,可以通过useEffect钩子和原生DOM事件监听滚动事件,获取滚动高度。以下是具体实现方式:
import React, { useState, useEffect } from 'react';
function ScrollComponent() {
const [scrollHeight, setScrollHeight] = useState(0);
useEffect(() => {
const handleScroll = () => {
setScrollHeight(window.pageYOffset || document.documentElement.scrollTop);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return <div>当前滚动高度: {scrollHeight}px</div>;
}
使用自定义Hook封装
为提高代码复用性,可以将滚动监听逻辑封装为自定义Hook:
import { useState, useEffect } from 'react';
function useScrollHeight() {
const [scrollHeight, setScrollHeight] = useState(0);
useEffect(() => {
const handleScroll = () => {
setScrollHeight(window.pageYOffset || document.documentElement.scrollTop);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return scrollHeight;
}
// 使用示例
function MyComponent() {
const scrollHeight = useScrollHeight();
return <div>滚动高度: {scrollHeight}px</div>;
}
监听特定容器的滚动高度
如果需要监听某个DOM元素(如div)的滚动高度而非整个页面,可以通过ref获取元素实例:
import React, { useState, useEffect, useRef } from 'react';
function ContainerScroll() {
const [scrollTop, setScrollTop] = useState(0);
const containerRef = useRef(null);
useEffect(() => {
const container = containerRef.current;
const handleScroll = () => {
setScrollTop(container.scrollTop);
};
container.addEventListener('scroll', handleScroll);
return () => container.removeEventListener('scroll', handleScroll);
}, []);
return (
<div ref={containerRef} style={{ height: '200px', overflow: 'auto' }}>
<div style={{ height: '1000px' }}>
容器内滚动高度: {scrollTop}px
</div>
</div>
);
}
性能优化建议
高频触发的滚动事件可能导致性能问题,可以通过节流(throttle)或防抖(debounce)优化:
import { throttle } from 'lodash';
function useScrollHeight() {
const [scrollHeight, setScrollHeight] = useState(0);
useEffect(() => {
const handleScroll = throttle(() => {
setScrollHeight(window.pageYOffset);
}, 100);
window.addEventListener('scroll', handleScroll);
return () => {
handleScroll.cancel();
window.removeEventListener('scroll', handleScroll);
};
}, []);
return scrollHeight;
}
兼容性注意事项
不同浏览器对滚动高度的获取方式可能不同,推荐使用以下兼容写法:

const scrollTop = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop
|| 0;






