react实现左右滑动
实现左右滑动的常见方法
使用第三方库(如 react-swipeable) 安装 react-swipeable 库:
npm install react-swipeable
示例代码:

import { useSwipeable } from 'react-swipeable';
function SwipeComponent() {
const handlers = useSwipeable({
onSwipedLeft: () => console.log('左滑'),
onSwipedRight: () => console.log('右滑'),
preventDefaultTouchmoveEvent: true,
trackMouse: true
});
return <div {...handlers}>滑动区域</div>;
}
使用原生 touch 事件 通过监听 touchstart、touchmove 和 touchend 事件实现:

function SwipeComponent() {
let touchStartX = 0;
const handleTouchStart = (e) => {
touchStartX = e.touches[0].clientX;
};
const handleTouchEnd = (e) => {
const touchEndX = e.changedTouches[0].clientX;
if (touchEndX < touchStartX) {
console.log('左滑');
} else if (touchEndX > touchStartX) {
console.log('右滑');
}
};
return (
<div
onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd}
>
滑动区域
</div>
);
}
使用 CSS Scroll Snap 纯 CSS 实现滑动效果:
function ScrollComponent() {
return (
<div style={{
overflowX: 'auto',
scrollSnapType: 'x mandatory',
display: 'flex'
}}>
<div style={{ scrollSnapAlign: 'start', flex: '0 0 100%' }}>页面1</div>
<div style={{ scrollSnapAlign: 'start', flex: '0 0 100%' }}>页面2</div>
</div>
);
}
使用 transform 动画 结合 useState 和 transform 实现平滑滑动:
import { useState } from 'react';
function TransformComponent() {
const [position, setPosition] = useState(0);
const handleSwipe = (direction) => {
const newPosition = direction === 'left' ? position - 100 : position + 100;
setPosition(newPosition);
};
return (
<div style={{ overflow: 'hidden' }}>
<div
style={{
display: 'flex',
transform: `translateX(${position}px)`,
transition: 'transform 0.3s ease'
}}
>
<div style={{ width: '100px' }}>内容1</div>
<div style={{ width: '100px' }}>内容2</div>
</div>
<button onClick={() => handleSwipe('left')}>左滑</button>
<button onClick={() => handleSwipe('right')}>右滑</button>
</div>
);
}
选择建议
- 需要简单手势检测时,推荐使用 react-swipeable
- 需要高性能原生实现时,使用 touch 事件方案
- 需要简单内容滑动时,CSS Scroll Snap 最轻量
- 需要自定义动画效果时,transform 方案最灵活
每种方案都可以根据具体需求进行扩展,例如添加滑动阈值判断、动画回调等。






