使用组件实现选项卡功能完整代码
时间: 2023-11-23 16:13:51 浏览: 28
好的,下面是一个完整的使用组件实现选项卡功能的代码示例:
```jsx
import { useState } from 'react';
function TabTitle({ title, index, activeIndex, onClick }) {
const isActive = index === activeIndex;
return (
<div onClick={() => onClick(index)}>
<h2 style={{ color: isActive ? 'red' : 'black' }}>{title}</h2>
</div>
);
}
function TabContent({ content, index, activeIndex }) {
if (index !== activeIndex) return null;
return <div>{content}</div>;
}
function Tabs() {
const [activeIndex, setActiveIndex] = useState(0);
const titles = ['Tab 1', 'Tab 2', 'Tab 3'];
const contents = ['Content 1', 'Content 2', 'Content 3'];
return (
<div>
{titles.map((title, index) => (
<TabTitle
key={index}
title={title}
index={index}
activeIndex={activeIndex}
onClick={(index) => setActiveIndex(index)}
/>
))}
{contents.map((content, index) => (
<TabContent
key={index}
content={content}
index={index}
activeIndex={activeIndex}
/>
))}
</div>
);
}
export default Tabs;
```
在上面的代码中,我们定义了 `TabTitle` 和 `TabContent` 组件来渲染选项卡的标题和内容。然后在 `Tabs` 组件中,我们使用 `useState` Hook 来创建一个状态变量 `activeIndex`,它用于跟踪当前选项卡的索引。我们使用 `map` 方法来遍历选项卡的标题和内容,然后分别创建 `TabTitle` 和 `TabContent` 组件,并通过回调函数将更新后的索引传递给父组件。最后,我们根据当前选项卡的索引来显示对应的内容。
你可以将这个代码复制到你的项目中,然后按照自己的需求进行修改和定制。