tdesign-react
tdesign-react copied to clipboard
[Swiper] 支持移动端左右滑动切换卡片
这个功能解决了什么问题
目前只支持点击按钮切换
你建议的方案是什么
支持移动端左右滑动切换卡片
👋 @li-b-y,感谢给 TDesign 提出了 issue。 请根据 issue 模版确保背景信息的完善,我们将调查并尽快回复你。
理论上 PC 端组件库不会特意新增这个 API...想要兼容移动端场景,可以考虑自己封装,参考代码如下
import React, { useRef, useState } from 'react';
import { Swiper } from 'tdesign-react';
const { SwiperItem } = Swiper;
export default function BasicSwiper() {
const swiperRef = useRef<HTMLDivElement>(null);
const touchStartX = useRef(0);
const touchEndX = useRef(0);
const [currentIndex, setCurrentIndex] = useState(0);
const swiperItems = [1, 2, 3, 4, 5, 6];
const handleTouchStart = (e: React.TouchEvent) => {
touchStartX.current = e.touches[0].clientX;
};
const handleTouchMove = (e: React.TouchEvent) => {
touchEndX.current = e.touches[0].clientX;
};
const handleTouchEnd = () => {
const swipeThreshold = 50;
const diff = touchStartX.current - touchEndX.current;
if (Math.abs(diff) > swipeThreshold) {
if (diff > 0) {
setCurrentIndex((prev) => (prev + 1) % swiperItems.length);
} else {
setCurrentIndex((prev) => (prev - 1 + swiperItems.length) % swiperItems.length);
}
}
touchStartX.current = 0;
touchEndX.current = 0;
};
return (
<div
ref={swiperRef}
className="tdesign-demo-block--swiper"
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
>
<Swiper autoplay={false} current={currentIndex} onChange={setCurrentIndex}>
{swiperItems.map((item) => (
<SwiperItem key={item}>
<div className="demo-item">{item}</div>
</SwiperItem>
))}
</Swiper>
</div>
);
}