react实现锚点
使用 useRef 创建锚点
在 React 中,可以通过 useRef 钩子创建对 DOM 元素的引用,实现锚点跳转。定义一个 ref 并将其绑定到目标元素上。
import { useRef } from 'react';
function Component() {
const targetRef = useRef(null);
const scrollToTarget = () => {
targetRef.current?.scrollIntoView({ behavior: 'smooth' });
};
return (
<div>
<button onClick={scrollToTarget}>跳转到锚点</button>
<div ref={targetRef} style={{ height: '1000px' }}>目标位置</div>
</div>
);
}
通过 id 属性实现传统锚点
直接使用 HTML 的 id 属性和 <a> 标签的 href 实现锚点跳转。适合静态页面或简单的场景。
function Component() {
return (
<div>
<a href="#target">跳转到锚点</a>
<div id="target" style={{ height: '1000px' }}>目标位置</div>
</div>
);
}
结合 React Router 实现路由锚点
在单页应用(SPA)中,可以通过 React Router 的 HashRouter 或 Link 组件实现路由级别的锚点跳转。
import { HashRouter as Router, Link } from 'react-router-dom';
function App() {
return (
<Router>
<Link to="#target">跳转到锚点</Link>
<div id="target" style={{ height: '1000px' }}>目标位置</div>
</Router>
);
}
动态锚点列表渲染
通过动态数据生成锚点列表,并实现跳转逻辑。适用于需要根据数据动态生成锚点的场景。
import { useRef } from 'react';
function Component() {
const sections = ['section1', 'section2', 'section3'];
const refs = sections.reduce((acc, section) => {
acc[section] = useRef(null);
return acc;
}, {});
const scrollToSection = (section) => {
refs[section].current?.scrollIntoView({ behavior: 'smooth' });
};
return (
<div>
{sections.map((section) => (
<button key={section} onClick={() => scrollToSection(section)}>
跳转到 {section}
</button>
))}
{sections.map((section) => (
<div key={section} ref={refs[section]} style={{ height: '500px' }}>
{section}
</div>
))}
</div>
);
}
注意事项
- 平滑滚动(
behavior: 'smooth')需要浏览器支持,部分旧版本浏览器可能不兼容。 - 动态生成的锚点需确保
ref或id的唯一性,避免冲突。 - 在
React Router中,锚点跳转可能需结合路由配置处理。







