# React中Swipe怎么用
## 目錄
1. [什么是Swipe手勢](#什么是swipe手勢)
2. [React中實現Swipe的常見方案](#react中實現swipe的常見方案)
3. [使用原生事件實現基礎Swipe](#使用原生事件實現基礎swipe)
4. [使用第三方庫react-swipeable](#使用第三方庫react-swipeable)
5. [完整代碼示例](#完整代碼示例)
6. [性能優化與注意事項](#性能優化與注意事項)
7. [常見問題解答](#常見問題解答)
---
## 什么是Swipe手勢
Swipe(滑動)是移動端常見的交互手勢,指用戶在觸摸屏上快速橫向或縱向滑動手指的操作。在React應用中,常用于實現:
- 輪播圖切換
- 卡片滑動刪除
- 頁面切換導航
- 手勢操作面板
---
## React中實現Swipe的常見方案
### 方案對比表
| 方案 | 優點 | 缺點 | 適用場景 |
|------|------|------|----------|
| 原生事件 | 零依賴,高性能 | 需要手動處理復雜邏輯 | 簡單手勢需求 |
| react-swipeable | 開箱即用,支持復雜手勢 | 增加包體積 | 需要完善手勢支持的項目 |
| Hammer.js | 功能全面 | 體積較大,需額外集成 | 專業級手勢應用 |
---
## 使用原生事件實現基礎Swipe
### 核心實現步驟
1. 監聽觸摸事件
2. 計算滑動方向和距離
3. 觸發回調函數
```jsx
import React, { useRef, useState } from 'react';
const SwipeComponent = () => {
const [swipeDirection, setSwipeDirection] = useState('');
const touchStart = useRef(null);
const touchEnd = useRef(null);
// 最小滑動距離閾值
const minSwipeDistance = 50;
const onTouchStart = (e) => {
touchEnd.current = null;
touchStart.current = e.targetTouches[0].clientX;
};
const onTouchMove = (e) => {
touchEnd.current = e.targetTouches[0].clientX;
};
const onTouchEnd = () => {
if (!touchStart.current || !touchEnd.current) return;
const distance = touchStart.current - touchEnd.current;
const isLeftSwipe = distance > minSwipeDistance;
const isRightSwipe = distance < -minSwipeDistance;
if (isLeftSwipe) {
setSwipeDirection('左滑');
// 執行左滑業務邏輯
} else if (isRightSwipe) {
setSwipeDirection('右滑');
// 執行右滑業務邏輯
}
};
return (
<div
style={{ width: '100%', height: '200px', background: '#eee' }}
onTouchStart={onTouchStart}
onTouchMove={onTouchMove}
onTouchEnd={onTouchEnd}
>
當前手勢:{swipeDirection || '未檢測到滑動'}
</div>
);
};
npm install react-swipeable
import { useSwipeable } from 'react-swipeable';
const SwipeableComponent = () => {
const handlers = useSwipeable({
onSwipedLeft: () => console.log('左滑觸發'),
onSwipedRight: () => console.log('右滑觸發'),
onSwipedUp: () => console.log('上滑觸發'),
onSwipedDown: () => console.log('下滑觸發'),
swipeDuration: 500,
preventDefaultTouchmoveEvent: true,
trackMouse: true // 支持鼠標拖動
});
return (
<div {...handlers} style={{ width: '100%', height: '300px', background: '#ddd' }}>
嘗試用鼠標或手指滑動
</div>
);
};
參數 | 類型 | 說明 |
---|---|---|
delta | number | 觸發滑動的最小距離(默認10) |
preventDefaultTouchmoveEvent | boolean | 是否阻止默認滾動行為 |
trackTouch | boolean | 是否跟蹤觸摸事件(默認true) |
rotationAngle | number | 允許的旋轉角度閾值 |
import { useState } from 'react';
import { useSwipeable } from 'react-swipeable';
const Carousel = ({ items }) => {
const [activeIndex, setActiveIndex] = useState(0);
const updateIndex = (newIndex) => {
// 處理循環邏輯
if (newIndex < 0) newIndex = items.length - 1;
else if (newIndex >= items.length) newIndex = 0;
setActiveIndex(newIndex);
};
const handlers = useSwipeable({
onSwipedLeft: () => updateIndex(activeIndex + 1),
onSwipedRight: () => updateIndex(activeIndex - 1),
trackMouse: true
});
return (
<div {...handlers} style={{ overflow: 'hidden' }}>
<div style={{
transform: `translateX(-${activeIndex * 100}%)`,
transition: 'transform 0.3s ease-out'
}}>
{items.map((item, index) => (
<div key={index}>{item}</div>
))}
</div>
<div className="indicators">
{items.map((_, index) => (
<button
key={index}
onClick={() => updateIndex(index)}
className={index === activeIndex ? 'active' : ''}
/>
))}
</div>
</div>
);
};
import { throttle } from 'lodash';
const throttledHandler = throttle((direction) => {
// 處理邏輯
}, 300);
touch-action: pan-y
確保垂直滾動不受影響.swipe-container {
touch-action: pan-x; /* 只允許橫向觸摸 */
}
const handlers = useSwipeable({
onSwipedLeft: () => {
// 顯示確認按鈕
setIsConfirmVisible(true);
},
delta: 60 // 需要滑動更遠距離
});
const handlers = useSwipeable({
onSwiping: ({ velocity }) => {
if (velocity > 0.5) {
// 快速滑動處理
}
}
});
提示:實際開發中建議根據項目需求選擇合適方案,簡單交互可用原生實現,復雜場景推薦使用成熟庫。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。