Tabs文档 https://ant.design/components/tabs-cn/
PropTypes类型 https://zh-hans.reactjs.org/docs/typechecking-with-proptypes.html

父组件使用 TabList

  1. function App({data}) {
  2. const [tabKey, setTabKey] = useState('Bar');
  3. const tabSource = useMemo(update, [data, tabKey]);
  4. function update() {
  5. return data.map(({ name, children }) => {
  6. return {
  7. label: name,
  8. value: name,
  9. element: (
  10. <CardChart
  11. dataSource={children}
  12. activeKey={tabKey}
  13. />
  14. )
  15. };
  16. });
  17. }
  18. return (
  19. <Tabs
  20. value={tabKey}
  21. dataSource={tabSource}
  22. onChange={setTabKey}
  23. tabBarStyle={{ fontWeight: 600 }}
  24. />
  25. )
  26. }

TabArray.js

TabArray 数据格式:

  1. [
  2. {label: '名称', value: '值', element: '子组件'}
  3. ]

TabArray

  1. import { useState } from 'react';
  2. import { array, func, bool, object, oneOf, elementType } from 'prop-types';
  3. import { Tabs } from 'antd';
  4. import classNames from 'classnames';
  5. import { Icon } from '@/components';
  6. const { TabPane } = Tabs;
  7. TabList.propTypes = {
  8. dataSource: array.isRequired,
  9. onChange: func,
  10. type: oneOf(['card', 'line', 'editable-card']),
  11. size: oneOf(['default', 'large', 'small']),
  12. tabPosition: oneOf(['top', 'right', 'bottom', 'left']),
  13. tabBarExtraContent: elementType,
  14. tabBarStyle: object,
  15. centered: bool,
  16. hideLine: bool
  17. };
  18. TabList.defaultProps = {
  19. type: 'line',
  20. centered: false,
  21. hideLine: false,
  22. tabPosition: 'top'
  23. };
  24. function TabList(props) {
  25. const {
  26. dataSource, onChange, value: key, className,
  27. tabPosition, tabBarStyle,
  28. size, type, tabBarExtraContent, centered, hideLine
  29. } = props;
  30. const [activeKey, setActiveKey] = useState(() => {
  31. return (key !== undefined) ? key : dataSource[0]?.value;
  32. });
  33. if (!Array.isArray(dataSource)) return null;
  34. function tabChange(value) {
  35. setActiveKey(value);
  36. if (onChange) onChange(value);
  37. }
  38. const attrs = {
  39. type,
  40. size,
  41. activeKey,
  42. onChange: tabChange,
  43. tabBarExtraContent,
  44. centered,
  45. tabPosition,
  46. tabBarStyle,
  47. className: classNames(className, { 'hide-before': hideLine })
  48. };
  49. return (
  50. <Tabs {...attrs}>
  51. {
  52. dataSource.map(({ label, value, icon, element }, i) => {
  53. const tab = icon ? <><Icon icon={icon} />{label}</> : label;
  54. return (
  55. <TabPane tab={tab} key={value}>
  56. {/* 如果不是当前的 Tab就不显示 */}
  57. {activeKey === value && element}
  58. </TabPane>
  59. );
  60. })
  61. }
  62. </Tabs>
  63. );
  64. }
  65. export default TabList;