点击tab切换后状态可以保持吗
时间: 2023-12-16 09:03:37 浏览: 39
是的,可以通过 `useState` 钩子来存储当前激活的标签状态,这样在切换标签时可以保持状态。
以下是修改后的示例代码:
```
import React, { useState } from 'react';
const Tab = ({ label, activeTab, onClick }) => {
const handleClick = () => {
onClick(label);
};
return (
<div
className={`tab ${activeTab === label ? 'active' : ''}`}
onClick={handleClick}
>
{label}
</div>
);
};
const Tabs = ({ children }) => {
const [activeTab, setActiveTab] = useState(children[0].props.label);
const onClickTab = (tab) => {
setActiveTab(tab);
};
return (
<div className="tabs">
<div className="tab-list">
{children.map((child) => {
const { label } = child.props;
return (
<Tab
key={label}
label={label}
activeTab={activeTab}
onClick={onClickTab}
/>
);
})}
</div>
<div className="tab-content">
{children.map((child) => {
if (child.props.label !== activeTab) return undefined;
return child.props.children;
})}
</div>
</div>
);
};
export default Tabs;
```
使用方式:
```
import React from 'react';
import Tabs from './Tabs';
const App = () => {
return (
<Tabs>
<div label="Tab 1">
Content of Tab 1
</div>
<div label="Tab 2">
Content of Tab 2
</div>
<div label="Tab 3">
Content of Tab 3
</div>
</Tabs>
);
};
export default App;
```
通过以上代码可以实现一个具有状态保持功能的多页签导航。
相关推荐
![](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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)