react实现tab滑动切换
实现 Tab 滑动切换的核心思路
使用 React 结合 CSS 或第三方库(如 react-swipeable)实现 Tab 内容的滑动切换效果。核心逻辑是通过状态管理当前激活的 Tab,并通过手势事件或动画库处理滑动交互。
方法一:纯 CSS + React 状态控制
通过 transform: translateX 实现滑动动画,结合 React 的 useState 管理 Tab 状态。
import React, { useState } from 'react';
import './TabSlider.css';
const TabSlider = () => {
const [activeTab, setActiveTab] = useState(0);
const tabs = ['Tab 1', 'Tab 2', 'Tab 3'];
return (
<div className="tab-container">
<div className="tab-header">
{tabs.map((tab, index) => (
<button
key={index}
className={`tab-button ${activeTab === index ? 'active' : ''}`}
onClick={() => setActiveTab(index)}
>
{tab}
</button>
))}
</div>
<div className="tab-content-wrapper">
<div
className="tab-content"
style={{ transform: `translateX(-${activeTab * 100}%)` }}
>
{tabs.map((tab, index) => (
<div key={index} className="tab-panel">
{`Content for ${tab}`}
</div>
))}
</div>
</div>
</div>
);
};
export default TabSlider;
CSS 关键部分:

.tab-content-wrapper {
overflow: hidden;
width: 100%;
}
.tab-content {
display: flex;
transition: transform 0.3s ease;
}
.tab-panel {
flex: 0 0 100%;
width: 100%;
}
方法二:使用 react-swipeable 库
通过手势事件实现滑动切换,需安装 react-swipeable:
npm install react-swipeable
代码示例:

import React, { useState } from 'react';
import { useSwipeable } from 'react-swipeable';
const SwipeableTabs = () => {
const [activeTab, setActiveTab] = useState(0);
const tabs = ['Tab 1', 'Tab 2', 'Tab 3'];
const handlers = useSwipeable({
onSwipedLeft: () =>
setActiveTab((prev) => Math.min(prev + 1, tabs.length - 1)),
onSwipedRight: () =>
setActiveTab((prev) => Math.max(prev - 1, 0)),
trackMouse: true,
});
return (
<div {...handlers}>
<div className="tab-buttons">
{tabs.map((tab, index) => (
<button
key={index}
onClick={() => setActiveTab(index)}
className={activeTab === index ? 'active' : ''}
>
{tab}
</button>
))}
</div>
<div className="tab-content" style={{ transform: `translateX(-${activeTab * 100}%)` }}>
{tabs.map((tab, index) => (
<div key={index} className="tab-panel">
{`Swiped Content for ${tab}`}
</div>
))}
</div>
</div>
);
};
方法三:结合 Framer Motion 动画
使用 framer-motion 实现更流畅的滑动动画:
npm install framer-motion
代码示例:
import { motion, AnimatePresence } from 'framer-motion';
const MotionTabs = () => {
const [activeTab, setActiveTab] = useState(0);
const tabs = ['Tab 1', 'Tab 2', 'Tab 3'];
return (
<div>
<div className="tab-buttons">
{tabs.map((tab, index) => (
<button
key={index}
onClick={() => setActiveTab(index)}
>
{tab}
</button>
))}
</div>
<AnimatePresence mode="wait">
<motion.div
key={activeTab}
initial={{ x: 300, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
exit={{ x: -300, opacity: 0 }}
transition={{ duration: 0.3 }}
>
{`Animated Content for ${tabs[activeTab]}`}
</motion.div>
</AnimatePresence>
</div>
);
};
注意事项
- 响应式设计:确保 Tab 容器宽度适应不同屏幕尺寸。
- 性能优化:避免在
tab-panel中渲染过重的内容,可考虑懒加载。 - 无障碍性:为 Tab 按钮添加
aria-selected和role="tablist"属性。






