qt-public-ui
Version:
新设计规范下业务组件库
94 lines • 3.05 kB
JavaScript
import React, { useState, useEffect } from 'react';
import { Spin } from 'antd';
import { HorizontalScroll, IndexCard } from '..';
import classnames from 'classnames';
var Group = function Group(props) {
var type = props.type,
onChange = props.onChange,
children = props.children,
style = props.style,
multiSelect = props.multiSelect,
_props$max = props.max,
max = _props$max === void 0 ? Infinity : _props$max,
_props$min = props.min,
min = _props$min === void 0 ? 0 : _props$min,
_props$loading = props.loading,
loading = _props$loading === void 0 ? false : _props$loading,
className = props.className;
var isControlled = ('value' in props);
var _useState = useState((isControlled ? props.value : props.defaultValue) || (multiSelect ? [] : '')),
activeKey = _useState[0],
setActiveKey = _useState[1];
var onCardClick = function onCardClick(key) {
if (multiSelect) {
var _activeKey = [].concat(activeKey);
var index = _activeKey.indexOf(key);
if (index > -1) {
// 如果存在就删除
// 判断是否超过限制
if (_activeKey.length > min) {
_activeKey.splice(index, 1);
onChange && onChange(_activeKey);
!isControlled && setActiveKey(_activeKey);
}
} else if (_activeKey.length < max) {
// 不存在就添加
_activeKey.length < max && _activeKey.push(key);
onChange && onChange(_activeKey);
!isControlled && setActiveKey(_activeKey);
}
} else {
activeKey !== key && onChange && onChange(key);
!isControlled && setActiveKey(key);
}
};
var getActive = function getActive(id) {
if (multiSelect) {
return activeKey != null && activeKey.indexOf(id) > -1;
} else {
return activeKey != null && id === activeKey;
}
};
useEffect(function () {
isControlled && setActiveKey(props.value);
}, [isControlled, props.value]);
if (!children) {
return null;
}
var renderCard = function renderCard(child) {
if (!child) return null;
var childProps = child.type === IndexCard ? {
key: child.props.id,
onClick: onCardClick,
isActive: getActive(child.props.id),
hasHook: multiSelect
} : {
key: child.props.id
};
return React.cloneElement(child, childProps);
};
var renderCards = function renderCards(childs) {
return childs.map(function (child) {
if (Array.isArray(child)) {
return renderCards(child);
}
return renderCard(child);
});
};
return /*#__PURE__*/React.createElement(Spin, {
spinning: loading
}, /*#__PURE__*/React.createElement(HorizontalScroll, {
isFlex: type === 'flex',
style: style,
className: classnames(className, 'umui-index-card-group')
}, Array.isArray(children) ? renderCards(children) : renderCard(children)));
};
Group.displayName = 'Group';
Group.defaultProps = {
type: 'default',
multiSelect: false,
max: Infinity,
min: 0,
loading: false
};
export default Group;