react实现左右滑动导航
使用 react-swipeable 实现左右滑动导航
安装 react-swipeable 库
npm install react-swipeable
创建可滑动导航组件
import { useSwipeable } from 'react-swipeable';
function SwipeableNav() {
const handlers = useSwipeable({
onSwipedLeft: () => console.log('向左滑动'),
onSwipedRight: () => console.log('向右滑动'),
preventDefaultTouchmoveEvent: true,
trackMouse: true
});
return (
<div {...handlers}>
{/* 导航内容 */}
</div>
);
}
使用 react-slick 实现轮播式导航
安装 react-slick
npm install react-slick slick-carousel
创建滑动导航组件

import Slider from 'react-slick';
function SlideNav() {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 3,
slidesToScroll: 1,
swipeToSlide: true,
responsive: [
{
breakpoint: 768,
settings: {
slidesToShow: 1
}
}
]
};
return (
<Slider {...settings}>
<div>导航项1</div>
<div>导航项2</div>
<div>导航项3</div>
</Slider>
);
}
使用纯CSS和React状态实现
创建自定义滑动组件
import { useState } from 'react';
function CustomSwipeNav() {
const [position, setPosition] = useState(0);
const [startX, setStartX] = useState(null);
const handleTouchStart = (e) => {
setStartX(e.touches[0].clientX);
};
const handleTouchMove = (e) => {
if (!startX) return;
const currentX = e.touches[0].clientX;
const diff = startX - currentX;
if (Math.abs(diff) > 50) {
setPosition(prev => diff > 0
? Math.min(prev + 100, 0)
: Math.max(prev - 100, -200));
setStartX(null);
}
};
return (
<div
style={{
overflow: 'hidden',
position: 'relative',
width: '100%'
}}
>
<div
style={{
display: 'flex',
transform: `translateX(${position}px)`,
transition: 'transform 0.3s ease'
}}
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
>
{[...Array(5)].map((_, i) => (
<div key={i} style={{ minWidth: '100px' }}>
导航项{i+1}
</div>
))}
</div>
</div>
);
}
使用 Framer Motion 实现动画滑动
安装 Framer Motion
npm install framer-motion
创建动画滑动导航

import { motion, useDragControls } from 'framer-motion';
function AnimatedSwipeNav() {
const dragControls = useDragControls();
return (
<motion.div
style={{
display: 'flex',
cursor: 'grab',
userSelect: 'none'
}}
drag="x"
dragConstraints={{ left: -200, right: 0 }}
dragControls={dragControls}
>
{[...Array(5)].map((_, i) => (
<motion.div
key={i}
style={{ minWidth: '100px' }}
whileTap={{ scale: 0.95 }}
>
导航项{i+1}
</motion.div>
))}
</motion.div>
);
}
性能优化建议
为滑动导航添加will-change属性提升性能
<div style={{ willChange: 'transform' }}>
{/* 导航内容 */}
</div>
使用React.memo优化组件性能
const MemoizedNavItem = React.memo(function NavItem({ text }) {
return <div>{text}</div>;
});
考虑使用虚拟滚动技术处理大量导航项
import { Virtuoso } from 'react-virtuoso';
function VirtualSwipeNav() {
return (
<Virtuoso
style={{ width: '100%', height: '50px' }}
totalCount={100}
itemContent={index => <div>导航项{index + 1}</div>}
overscan={3}
/>
);
}






