react如何滚动scroll
React 实现滚动的方法
使用 useRef 和 scrollTo 方法
通过 useRef 获取 DOM 元素的引用,调用 scrollTo 方法实现滚动。
import React, { useRef } from 'react';
function ScrollComponent() {
const scrollRef = useRef(null);
const scrollToBottom = () => {
scrollRef.current.scrollTo({
top: scrollRef.current.scrollHeight,
behavior: 'smooth'
});
};
return (
<div>
<div ref={scrollRef} style={{ height: '200px', overflow: 'auto' }}>
{/* 长内容 */}
</div>
<button onClick={scrollToBottom}>滚动到底部</button>
</div>
);
}
使用 window.scrollTo 实现全局滚动
直接操作 window 对象实现页面全局滚动。

const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
};
使用第三方库 react-scroll
安装 react-scroll 库后,可以通过组件或函数实现滚动。
import { Link, animateScroll as scroll } from 'react-scroll';
// 组件方式
<Link to="section1" smooth={true} duration={500}>滚动到 Section 1</Link>
// 函数方式
scroll.scrollToBottom({ duration: 500, smooth: true });
使用 scrollIntoView 方法
通过 DOM 元素的 scrollIntoView 方法实现滚动到指定元素。

const scrollToElement = () => {
const element = document.getElementById('target');
element.scrollIntoView({ behavior: 'smooth' });
};
监听滚动事件
通过 useEffect 监听滚动事件,实现自定义滚动逻辑。
import React, { useEffect } from 'react';
function ScrollListener() {
useEffect(() => {
const handleScroll = () => {
console.log(window.scrollY);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return <div style={{ height: '2000px' }}>长内容</div>;
}
自定义滚动钩子
封装自定义 Hook 复用滚动逻辑。
import { useState, useEffect } from 'react';
function useScroll() {
const [scrollY, setScrollY] = useState(0);
useEffect(() => {
const handleScroll = () => setScrollY(window.scrollY);
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return scrollY;
}
注意事项
- 平滑滚动需浏览器支持
behavior: 'smooth',否则需使用 polyfill。 - 避免频繁触发滚动事件,可能导致性能问题。
- 第三方库如
react-scroll提供更多高级功能,适合复杂场景。






