react 实现选项卡
实现选项卡的基本结构
使用 React 的 useState 管理当前选中的选项卡索引,并通过条件渲染切换内容。

import React, { useState } from 'react';
const TabComponent = () => {
const [activeTab, setActiveTab] = useState(0);
const tabs = ['Tab 1', 'Tab 2', 'Tab 3'];
const contents = [
<div>Content for Tab 1</div>,
<div>Content for Tab 2</div>,
<div>Content for Tab 3</div>
];
return (
<div>
<div style={{ display: 'flex' }}>
{tabs.map((tab, index) => (
<button
key={index}
onClick={() => setActiveTab(index)}
style={{
padding: '10px',
background: activeTab === index ? 'lightblue' : 'white',
border: '1px solid gray'
}}
>
{tab}
</button>
))}
</div>
<div style={{ padding: '20px', border: '1px solid gray' }}>
{contents[activeTab]}
</div>
</div>
);
};
export default TabComponent;
封装可复用的选项卡组件
将选项卡逻辑抽象为独立组件,提高复用性。

import React, { useState } from 'react';
const Tabs = ({ tabs, defaultIndex = 0, children }) => {
const [activeTab, setActiveTab] = useState(defaultIndex);
return (
<div>
<div style={{ display: 'flex' }}>
{tabs.map((tab, index) => (
<button
key={index}
onClick={() => setActiveTab(index)}
style={{
padding: '10px',
background: activeTab === index ? 'lightblue' : 'white',
border: '1px solid gray'
}}
>
{tab}
</button>
))}
</div>
<div style={{ padding: '20px', border: '1px solid gray' }}>
{children[activeTab]}
</div>
</div>
);
};
// 使用示例
const App = () => (
<Tabs tabs={['Tab A', 'Tab B']}>
<div>Content A</div>
<div>Content B</div>
</Tabs>
);
添加动画效果
通过 CSS 或动画库(如 framer-motion)实现平滑切换效果。
import { motion, AnimatePresence } from 'framer-motion';
const AnimatedTabContent = ({ activeTab, contents }) => (
<AnimatePresence mode="wait">
<motion.div
key={activeTab}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.3 }}
>
{contents[activeTab]}
</motion.div>
</AnimatePresence>
);
响应式设计优化
使用 CSS 媒体查询或 Flexbox/Grid 布局适配不同屏幕尺寸。
/* 示例 CSS */
.tab-container {
display: flex;
flex-wrap: wrap;
}
.tab-button {
flex: 1;
min-width: 100px;
}
@media (max-width: 600px) {
.tab-button {
flex: 100%;
}
}






