react点击实现锚点
使用 ref 定位元素
在 React 中可以通过 useRef 创建引用,绑定到目标 DOM 元素上。点击按钮时调用 scrollIntoView 方法实现平滑滚动。
import { useRef } from 'react';
function Component() {
const targetRef = useRef(null);
const handleClick = () => {
targetRef.current?.scrollIntoView({ behavior: 'smooth' });
};
return (
<div>
<button onClick={handleClick}>跳转到目标</button>
<div ref={targetRef} style={{ height: '1000px' }}>
目标区域
</div>
</div>
);
}
使用原生 ID 锚点
传统 HTML 锚点方式在 React 中同样适用,通过 a 标签的 href 属性指向目标元素的 ID。
function Component() {
return (
<div>
<a href="#section">跳转到目标</a>
<div id="section" style={{ height: '1000px' }}>
目标区域
</div>
</div>
);
}
路由结合锚点
在 React Router 环境中,可以通过 HashRouter 实现页面内锚点跳转。
import { HashRouter as Router, Link } from 'react-router-dom';
function App() {
return (
<Router>
<Link to="#section">跳转</Link>
<div id="section">目标内容</div>
</Router>
);
}
第三方库实现
使用 react-scroll 库提供更丰富的滚动功能,支持偏移量、动画时间等配置。
import { Link } from 'react-scroll';
function Component() {
return (
<div>
<Link to="section" smooth={true} duration={500}>
平滑滚动
</Link>
<div name="section" style={{ height: '1000px' }}>
目标区域
</div>
</div>
);
}
注意事项
- 平滑滚动需要浏览器支持
scroll-behavior: smooth - 目标元素需要确保已渲染完成
- 在 SSR 场景下需要考虑客户端 hydrate 后的可用性
- 滚动容器非 body 时需要指定容器元素的引用
以上方法可根据具体场景选择使用,现代浏览器均已良好支持原生平滑滚动 API。






