react如何调至锚点
使用 useRef 和 scrollIntoView
在 React 中可以通过 useRef 创建引用,并将该引用绑定到目标元素上。调用 scrollIntoView 方法实现锚点跳转。

import { useRef } from 'react';
function App() {
const sectionRef = useRef(null);
const scrollToSection = () => {
sectionRef.current.scrollIntoView({ behavior: 'smooth' });
};
return (
<div>
<button onClick={scrollToSection}>跳转到锚点</button>
<div ref={sectionRef} style={{ height: '1000px' }}>
目标区域
</div>
</div>
);
}
使用 react-router-hash-link 库
对于使用 React Router 的项目,可以通过 react-router-hash-link 库简化哈希锚点的实现。该库直接兼容 React Router 的路由系统。

import { HashLink as Link } from 'react-router-hash-link';
function App() {
return (
<div>
<Link to="#section">跳转到锚点</Link>
<div id="section" style={{ height: '1000px' }}>
目标区域
</div>
</div>
);
}
动态生成锚点链接
通过遍历数据动态生成锚点链接和对应内容区域,适用于需要批量创建锚点的场景。
import { useRef } from 'react';
const sections = ['section1', 'section2', 'section3'];
function App() {
const refs = sections.reduce((acc, section) => {
acc[section] = useRef(null);
return acc;
}, {});
return (
<div>
{sections.map((section) => (
<button
key={section}
onClick={() => refs[section].current.scrollIntoView()}
>
{section}
</button>
))}
{sections.map((section) => (
<div key={section} ref={refs[section]} style={{ height: '500px' }}>
{section}
</div>
))}
</div>
);
}
监听路由变化实现锚点
在 React Router 环境中,可以通过监听路由的哈希变化自动滚动到对应位置。
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
function App() {
const location = useLocation();
useEffect(() => {
if (location.hash) {
const element = document.getElementById(location.hash.substring(1));
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
}
}, [location]);
return (
<div>
<a href="#section">跳转到锚点</a>
<div id="section" style={{ height: '1000px' }}>
目标区域
</div>
</div>
);
}
注意事项
- 平滑滚动效果需要浏览器支持
behavior: 'smooth'参数 - 使用
scrollIntoView时需确保目标元素已完成渲染 - 在 SSR 环境中需要做兼容处理,避免服务端执行 DOM 操作
- 锚点元素的
id应当避免使用特殊字符
以上方法可根据具体项目需求选择使用。基于 useRef 的方案最通用,而 react-router-hash-link 则更适合 React Router 项目。动态锚点适用于内容动态生成的场景,路由监听方案则实现了 URL 与页面位置的同步。






