react写一个tab切换
时间: 2023-07-20 18:33:41 浏览: 55
好的,下面是一个简单的React实现的Tab切换组件:
```jsx
import React, { useState } from "react";
function TabSwitcher(props) {
const [activeIndex, setActiveIndex] = useState(0);
const handleTabClick = (index) => {
setActiveIndex(index);
};
return (
<div>
<ul>
{props.tabs.map((tab, index) => (
<li
key={index}
className={index === activeIndex ? "active" : ""}
onClick={() => handleTabClick(index)}
>
{tab.title}
</li>
))}
</ul>
{props.tabs[activeIndex].content}
</div>
);
}
export default TabSwitcher;
```
使用方式:
```jsx
import React from "react";
import TabSwitcher from "./TabSwitcher";
function App() {
const tabs = [
{
title: "Tab 1",
content: <div>Content 1</div>,
},
{
title: "Tab 2",
content: <div>Content 2</div>,
},
{
title: "Tab 3",
content: <div>Content 3</div>,
},
];
return (
<div>
<TabSwitcher tabs={tabs} />
</div>
);
}
export default App;
```
其中,`tabs` 是一个数组,每个元素包含 `title` 和 `content` 两个属性。`title` 是标签的显示文本,`content` 是对应标签的内容。组件内部使用 `useState` 来维护当前选中标签的索引,当点击某个标签时,会更新 `activeIndex` 的值,从而触发组件重新渲染。根据 `activeIndex` 的值,动态添加 `active` 类名来控制选中标签的样式,同时渲染对应标签的内容。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)