react 锚点实现
使用 useRef 和 scrollIntoView
在 React 中,可以通过 useRef 创建引用,并将该引用绑定到目标元素上。调用 scrollIntoView 方法实现滚动到指定位置。
import React, { useRef } from 'react';
function ScrollDemo() {
const sectionRef = useRef(null);
const scrollToSection = () => {
sectionRef.current.scrollIntoView({ behavior: 'smooth' });
};
return (
<div>
<button onClick={scrollToSection}>Scroll to Section</button>
<div style={{ height: '1000px' }}>Some content</div>
<div ref={sectionRef}>Target Section</div>
</div>
);
}
使用 react-scroll 库
react-scroll 是一个专门为 React 设计的滚动库,支持平滑滚动和锚点功能。
import { Link, animateScroll as scroll } from 'react-scroll';
function ScrollDemo() {
return (
<div>
<Link to="section" smooth={true} duration={500}>
Scroll to Section
</Link>
<div style={{ height: '1000px' }}>Some content</div>
<div name="section">Target Section</div>
</div>
);
}
使用 HTML ID 和原生方法
通过设置元素的 id,可以直接使用原生 DOM 方法实现锚点跳转。
function ScrollDemo() {
const scrollToSection = () => {
const element = document.getElementById('section');
element.scrollIntoView({ behavior: 'smooth' });
};
return (
<div>
<button onClick={scrollToSection}>Scroll to Section</button>
<div style={{ height: '1000px' }}>Some content</div>
<div id="section">Target Section</div>
</div>
);
}
动态锚点实现
如果需要动态生成锚点,可以通过遍历数据并绑定 ref 或 id 实现。
import React, { useRef } from 'react';
function DynamicScrollDemo() {
const items = ['Section 1', 'Section 2', 'Section 3'];
const refs = useRef(items.map(() => React.createRef()));
const scrollTo = (index) => {
refs.current[index].scrollIntoView({ behavior: 'smooth' });
};
return (
<div>
{items.map((item, index) => (
<button key={index} onClick={() => scrollTo(index)}>
Scroll to {item}
</button>
))}
<div style={{ height: '1000px' }}>Some content</div>
{items.map((item, index) => (
<div key={index} ref={refs.current[index]}>
{item}
</div>
))}
</div>
);
}






