如何获取可滚动组件的当前滚动偏移量
在React中,你可以使用ref来获取可滚动组件的当前滚动偏移量。以下是一个示例:
import React, { useRef, useEffect } from 'react';
const ScrollableComponent = () => {
const scrollRef = useRef(null);
useEffect(() => {
const scrollPosition = scrollRef.current.scrollTop;
console.log(`Scroll position: ${scrollPosition}`);
}, []);
return (
<div ref={scrollRef} style={{ height: '2000px', overflowY: 'scroll' }}>
<p>Scrollable content goes here...</p>
</div>
);
};
export default ScrollableComponent;
在这个示例中,我们首先使用useRef
hook 创建一个 ref,并将其存储在scrollRef
变量中。然后,在useEffect
hook 中,我们可以通过scrollRef.current.scrollTop
获取滚动位置。注意,scrollTop
属性返回元素的顶部偏移量,如果元素没有滚动,则返回 0。
解决措施
参考链接
Scroll