react 写一个tab切换栏
时间: 2023-10-10 09:13:21 浏览: 118
好的,以下是一个简单的 React Tab 切换栏的示例代码:
```jsx
import React, { useState } from 'react';
const TabSwitcher = ({ tabs }) => {
const [activeTab, setActiveTab] = useState(0);
const switchTab = index => {
setActiveTab(index);
};
return (
<div className="tab-switcher">
<div className="tabs">
{tabs.map((tab, index) => (
<button
key={index}
onClick={() => switchTab(index)}
className={activeTab === index ? 'active' : ''}
>
{tab.title}
</button>
))}
</div>
<div className="tab-content">{tabs[activeTab].content}</div>
</div>
);
};
export default TabSwitcher;
```
使用方法:
```jsx
import React from 'react';
import TabSwitcher from './TabSwitcher';
const tabs = [
{
title: 'Tab 1',
content: <p>This is the content for Tab 1</p>
},
{
title: 'Tab 2',
content: <p>This is the content for Tab 2</p>
},
{
title: 'Tab 3',
content: <p>This is the content for Tab 3</p>
}
];
const App = () => {
return (
<div>
<h1>Tab Switcher Demo</h1>
<TabSwitcher tabs={tabs} />
</div>
);
};
export default App;
```
这个组件包含一个状态 `activeTab`,用于跟踪当前选中的选项卡。通过点击选项卡按钮,可以使用 `setActiveTab` 函数来更新状态并显示相应的内容。
阅读全文