react如何调至锚点
使用 useRef 和 scrollIntoView
在 React 中,可以通过 useRef 钩子创建引用,并将其绑定到目标元素上。调用 scrollIntoView 方法实现平滑滚动到锚点位置。

import { useRef } from 'react';
function ScrollToAnchor() {
const targetRef = useRef(null);
const scrollToTarget = () => {
targetRef.current?.scrollIntoView({ behavior: 'smooth' });
};
return (
<div>
<button onClick={scrollToTarget}>滚动到目标</button>
<div style={{ height: '1000px' }}></div>
<div ref={targetRef}>目标锚点位置</div>
</div>
);
}
结合 React Router 的 Hash 链接
如果项目使用 React Router,可以通过 HashLink 组件或直接操作 window.location.hash 实现基于 URL 哈希的锚点跳转。

import { HashLink } from 'react-router-hash-link';
function Navigation() {
return (
<nav>
<HashLink smooth to="#section1">
跳转到第一节
</HashLink>
</nav>
);
}
function Content() {
return (
<div id="section1">
<h2>第一节内容</h2>
</div>
);
}
自定义滚动行为
对于需要更复杂滚动控制的场景,可以封装自定义滚动函数,考虑边界条件或添加动画效果。
const smoothScroll = (ref, offset = 0) => {
const elementPosition = ref.current.offsetTop;
window.scrollTo({
top: elementPosition - offset,
behavior: 'smooth'
});
};
注意事项
- 确保目标元素已正确渲染后再执行滚动操作,可在
useEffect中处理 - 移动端可能需要考虑浏览器兼容性问题
- 对于固定导航栏的情况,需计算偏移量避免内容被遮挡






