react实现整屏滚动
React 实现整屏滚动
整屏滚动(Full Page Scroll)是一种常见的网页交互效果,用户每次滚动鼠标或触摸屏幕时,页面会平滑地滚动到下一个完整视口高度的部分。以下是几种实现方法:
使用 react-full-page 库
react-full-page 是一个专门用于实现整屏滚动的 React 组件库,支持触摸和鼠标滚轮事件。
安装依赖:
npm install react-full-page
示例代码:
import React from 'react';
import { FullPage, Slide } from 'react-full-page';
const App = () => {
return (
<FullPage>
<Slide style={{ backgroundColor: '#ff5f45' }}>
<h1>第一屏</h1>
</Slide>
<Slide style={{ backgroundColor: '#0798ec' }}>
<h1>第二屏</h1>
</Slide>
<Slide style={{ backgroundColor: '#fc6c7c' }}>
<h1>第三屏</h1>
</Slide>
</FullPage>
);
};
export default App;
使用 CSS 和 React 状态控制
通过 CSS 的 scroll-snap 属性和 React 的状态管理实现。
CSS 部分:
.container {
height: 100vh;
overflow-y: scroll;
scroll-snap-type: y mandatory;
}
.section {
height: 100vh;
scroll-snap-align: start;
}
React 组件:
import React from 'react';
import './styles.css';
const App = () => {
return (
<div className="container">
<div className="section" style={{ backgroundColor: '#ff5f45' }}>
<h1>第一屏</h1>
</div>
<div className="section" style={{ backgroundColor: '#0798ec' }}>
<h1>第二屏</h1>
</div>
<div className="section" style={{ backgroundColor: '#fc6c7c' }}>
<h1>第三屏</h1>
</div>
</div>
);
};
export default App;
使用 react-scroll 库
react-scroll 提供了更灵活的滚动控制,支持动画和锚点跳转。
安装依赖:
npm install react-scroll
示例代码:
import React from 'react';
import { Link, animateScroll as scroll } from 'react-scroll';
const App = () => {
return (
<div>
<Link to="section1" smooth={true} duration={500}>
跳转到第一屏
</Link>
<div id="section1" style={{ height: '100vh', backgroundColor: '#ff5f45' }}>
<h1>第一屏</h1>
</div>
<div id="section2" style={{ height: '100vh', backgroundColor: '#0798ec' }}>
<h1>第二屏</h1>
</div>
</div>
);
};
export default App;
自定义实现
通过监听滚动事件和手动控制滚动位置实现。
示例代码:

import React, { useState, useEffect } from 'react';
const App = () => {
const [currentSection, setCurrentSection] = useState(0);
useEffect(() => {
const handleWheel = (e) => {
e.preventDefault();
const direction = e.deltaY > 0 ? 1 : -1;
const newSection = Math.max(0, Math.min(2, currentSection + direction));
setCurrentSection(newSection);
window.scrollTo({
top: newSection * window.innerHeight,
behavior: 'smooth',
});
};
window.addEventListener('wheel', handleWheel, { passive: false });
return () => window.removeEventListener('wheel', handleWheel);
}, [currentSection]);
return (
<div>
<div style={{ height: '100vh', backgroundColor: '#ff5f45' }}>
<h1>第一屏</h1>
</div>
<div style={{ height: '100vh', backgroundColor: '#0798ec' }}>
<h1>第二屏</h1>
</div>
<div style={{ height: '100vh', backgroundColor: '#fc6c7c' }}>
<h1>第三屏</h1>
</div>
</div>
);
};
export default App;
注意事项
- 性能优化:避免在滚动事件中频繁触发重渲染,使用防抖或节流技术。
- 移动端适配:确保触摸事件的处理与鼠标滚轮事件一致。
- 无障碍访问:为屏幕阅读器提供适当的 ARIA 属性。
以上方法可以根据项目需求选择,库封装的方式更适合快速开发,而自定义实现则提供更高的灵活性。






