UNPKG

sailboat-design

Version:
81 lines (80 loc) 3.34 kB
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime"; import classNames from 'classnames'; import React, { useState, createContext, useRef, useEffect } from 'react'; import ActiveBar, { activeBarDisplayName } from './activeBar'; import { tabDisplayName } from './tab'; export var TabsContext = createContext({}); /** * 使用选项卡,你可以轻松地浏览和切换不同的视图。 * ### 引入方式 * ~~~js * import { Tabs, Tab, TabPanel } from '@sailboat'; * ~~~ * * 对于在同一层次,并且息息相关的内容组,使用选项卡能够将它们分组并且在其之间切换。 */ export var Tabs = function (props) { var _a; var children = props.children, value = props.value, onChange = props.onChange, className = props.className, style = props.style, type = props.type; var _b = useState(value || 0), activeIndex = _b[0], setActiveIndex = _b[1]; var _c = useState(0), forceRenderState = _c[0], setForceRenderState = _c[1]; var tabsRef = useRef(null); var _d = useState(null), refState = _d[0], setRefState = _d[1]; var classes = classNames('sail-tabs', className, (_a = {}, // [`sail-tabs_${mode}`]: mode !== 'horizontal' && type !== 'card', _a['sail-tabs_card'] = type === 'card', _a)); var handleChange = function (index) { setActiveIndex(index); if (onChange) { onChange(index); } }; var passedContext = { onChange: handleChange, activeIndex: activeIndex, tabsDom: tabsRef.current, mode: 'horizontal', forceRenderCallback: function () { if (type === 'card') { return; } setForceRenderState(forceRenderState + 1); } }; useEffect(function () { if (!tabsRef.current) { return; } setRefState(tabsRef.current); }, [tabsRef.current]); // 克隆子元素, 添加index, 判断类型是否是 var renderChildren = React.Children.map(children, function (child, index) { var childElement = child; var displayName = childElement.type.displayName; if (displayName !== tabDisplayName && displayName !== activeBarDisplayName) { console.error('Warning: Menu has a child which is not a Tab component.'); return null; } return React.cloneElement(child, { index: index }); }); return (_jsx("ul", __assign({ className: classes, style: style, ref: tabsRef }, { children: _jsx(TabsContext.Provider, __assign({ value: passedContext }, { children: _jsxs(_Fragment, { children: [renderChildren, type !== 'card' && _jsx(ActiveBar, { forceRenderState: forceRenderState })] }) })) }))); }; Tabs.defaultProps = { mode: 'horizontal', type: 'border' }; export default Tabs;