react页面实现全屏滚动
实现全屏滚动的 React 方案
使用 react-full-page 库
安装 react-full-page 库:
npm install react-full-page
示例代码:

import React from 'react';
import { FullPage, Slide } from 'react-full-page';
const App = () => {
return (
<FullPage>
<Slide>
<div style={{ backgroundColor: 'red', height: '100vh' }}>Section 1</div>
</Slide>
<Slide>
<div style={{ backgroundColor: 'blue', height: '100vh' }}>Section 2</div>
</Slide>
<Slide>
<div style={{ backgroundColor: 'green', height: '100vh' }}>Section 3</div>
</Slide>
</FullPage>
);
};
使用 react-scroll 库
安装 react-scroll 库:
npm install react-scroll
示例代码:

import React from 'react';
import { Link, animateScroll as scroll } from 'react-scroll';
const App = () => {
return (
<div>
<nav>
<Link to="section1" smooth={true} duration={500}>Section 1</Link>
<Link to="section2" smooth={true} duration={500}>Section 2</Link>
<Link to="section3" smooth={true} duration={500}>Section 3</Link>
</nav>
<div id="section1" style={{ height: '100vh', backgroundColor: 'red' }}>Section 1</div>
<div id="section2" style={{ height: '100vh', backgroundColor: 'blue' }}>Section 2</div>
<div id="section3" style={{ height: '100vh', backgroundColor: 'green' }}>Section 3</div>
</div>
);
};
自定义实现方案
通过监听滚动事件和 CSS 实现:
import React, { useState, useEffect } from 'react';
const App = () => {
const [currentSection, setCurrentSection] = useState(0);
const sections = ['red', 'blue', 'green'];
useEffect(() => {
const handleWheel = (e) => {
if (e.deltaY > 0) {
setCurrentSection(prev => Math.min(prev + 1, sections.length - 1));
} else {
setCurrentSection(prev => Math.max(prev - 1, 0));
}
};
window.addEventListener('wheel', handleWheel);
return () => window.removeEventListener('wheel', handleWheel);
}, []);
return (
<div style={{ overflow: 'hidden', height: '100vh' }}>
{sections.map((color, index) => (
<div
key={index}
style={{
transform: `translateY(-${currentSection * 100}vh)`,
transition: 'transform 0.5s ease',
height: '100vh',
backgroundColor: color
}}
>
Section {index + 1}
</div>
))}
</div>
);
};
CSS-only 解决方案
使用纯 CSS 的 scroll-snap 属性:
import React from 'react';
const App = () => {
return (
<div style={{
height: '100vh',
overflowY: 'scroll',
scrollSnapType: 'y mandatory'
}}>
<div style={{
height: '100vh',
scrollSnapAlign: 'start',
backgroundColor: 'red'
}}>Section 1</div>
<div style={{
height: '100vh',
scrollSnapAlign: 'start',
backgroundColor: 'blue'
}}>Section 2</div>
<div style={{
height: '100vh',
scrollSnapAlign: 'start',
backgroundColor: 'green'
}}>Section 3</div>
</div>
);
};
注意事项
- 移动端兼容性需要考虑触摸事件处理
- 性能优化:避免频繁的 DOM 操作和重绘
- 可访问性:确保键盘导航和屏幕阅读器支持
- 浏览器兼容性:某些 CSS 属性可能需要前缀
以上方案可根据项目需求选择,库方案更完整但体积较大,自定义方案更灵活但需要处理更多细节。






