react实现锚点滚动
使用 scrollIntoView 方法
在 React 中可以通过 useRef 获取 DOM 元素,并调用 scrollIntoView 方法实现平滑滚动。以下是一个示例代码:

import React, { useRef } from 'react';
function ScrollDemo() {
const sectionRef = useRef(null);
const scrollToSection = () => {
sectionRef.current?.scrollIntoView({ behavior: 'smooth' });
};
return (
<div>
<button onClick={scrollToSection}>滚动到目标区域</button>
<div style={{ height: '1000px' }}>占位内容</div>
<div ref={sectionRef}>目标区域</div>
</div>
);
}
使用 react-scroll 库
react-scroll 是一个专门用于 React 滚动的第三方库,提供更多配置选项:
import { Link } from 'react-scroll';
function ScrollDemo() {
return (
<div>
<Link
to="targetSection"
smooth={true}
duration={500}
>
滚动到目标区域
</Link>
<div style={{ height: '1000px' }}>占位内容</div>
<div name="targetSection">目标区域</div>
</div>
);
}
自定义滚动逻辑
如果需要更精细的控制,可以手动计算位置并设置滚动:
import React, { useRef } from 'react';
function ScrollDemo() {
const containerRef = useRef(null);
const targetRef = useRef(null);
const scrollToTarget = () => {
const container = containerRef.current;
const target = targetRef.current;
if (container && target) {
const targetPosition = target.offsetTop - container.offsetTop;
container.scrollTo({
top: targetPosition,
behavior: 'smooth'
});
}
};
return (
<div ref={containerRef} style={{ height: '300px', overflow: 'auto' }}>
<button onClick={scrollToTarget}>滚动到目标</button>
<div style={{ height: '1000px' }}>占位内容</div>
<div ref={targetRef}>目标区域</div>
</div>
);
}
注意事项
- 平滑滚动需要浏览器支持
behavior: 'smooth'属性 - 在 SSR 场景下需要确保 DOM 已加载完成再执行滚动操作
- 对于复杂布局可能需要计算额外的偏移量(如固定头部的高度)
以上方法可根据具体需求选择使用,react-scroll 提供了最完整的解决方案,而原生 API 则更轻量。







