一.組件代碼
tabs/index.tsx文件
import React, { useState } from 'react';
import { TabBar, TabContent, TabBarItem } from './styled';
interface PropsInter {
defaultActiveKey?: any;
disabled?: boolean;
onChange?: (activeKey: any) => any;
}
function TabPane(props: any) {
return <div>{props.children}</div>;
}
function Tabs(props: PropsInter) {
const [currentIndex, setCurrentIndex] = useState(props.defaultActiveKey);
const onChange = (activeKey: any) => {
if (typeof props.onChange === 'function') props.onChange(activeKey);
setCurrentIndex(activeKey);
};
return (
<div style={{ overflow: 'hidden' }}>
<TabBar>
{React.Children.map(props.children, (element, index) => {
let { disabled, tab } = element.props;
return (
<TabBarItem
className={currentIndex === element.key ? 'active' : ''}
onClick={() => onChange(element.key)}
key={element.key}
disabled={disabled}
>
{tab}
</TabBarItem>
);
})}
</TabBar>
<TabContent>
{React.Children.map(props.children, (element, index) => {
return (
<div
key={element.key}
style={{
display: currentIndex === element.key ? 'block' : 'none',
}}
>
{element}
</div>
);
})}
</TabContent>
</div>
);
}
export { Tabs, TabPane };
tabs/styled.ts文件
import styled from 'styled-components'; import { Button } from 'antd'; export const TabBar = styled.div` background: #fff; padding: 8px 16px; z-index: 1; flex-shrink: 0; display: flex; position: relative; `; export const TabBarItem = styled(Button)` margin: 0 34px 0 0; padding: 12px 0px; font-size: 14px; display: flex; justify-content: center; align-items: center; box-sizing: border-box; border: none; box-shadow: none; &.active, &.hover { color: #108ee9; border-bottom: 2px solid #1890ff; } `; export const TabContent = styled.div` background: #fff; display: flex; flex: 1; height: 100%; div { flex-shrink: 0; width: 100%; overflow-y: auto; } `;
二.使用組件:
import React from 'react'; import { Tabs, TabPane } from './tabs'; export interface BasicLayoutProps {} const BasicLayout: React.FC<BasicLayoutProps> = props => { const { children } = props; return ( <> <Tabs defaultActiveKey="1" onChange={activeKey => console.log('activeKey', activeKey)} > <div tab="A00000" key="1"> <TabPane>A 選修卡的內容</TabPane> </div> <TabPane tab="B" key="2"> B 選修卡的內容 </TabPane> <TabPane tab="399999" key="3"> c 選修卡的內容 </TabPane> </Tabs> </> ); }; export default BasicLayout;
三.結果圖解:

四.組件內容詳解
1.Tabs組件控制tab欄切換 TabPane展示tab真實內容
2.React.Children.map結構:React.Children.map(object children,callback)
如:React.Children.map(props.children, (element, index) => {}
props.children:=>子元素集合數組 這里是Tabs里面的內容

element:=>子組件數組的每一個子項 這里是每一個TabPane里面的內容

