zarm
Version:
基于 React 的移动端UI库
82 lines (72 loc) • 2.93 kB
JavaScript
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import { createBEM } from '@zarm-design/bem';
import React, { useContext, useEffect, useState } from 'react';
import isEqual from 'lodash/isEqual';
import { ConfigContext } from '../config-provider';
import List from '../list';
import { CheckboxGroupContext } from './context';
var getValue = function getValue(props, defaultValue) {
var _ref, _props$value;
return (_ref = (_props$value = props.value) !== null && _props$value !== void 0 ? _props$value : props.defaultValue) !== null && _ref !== void 0 ? _ref : defaultValue;
};
var CheckboxGroup = function CheckboxGroup(props) {
var _ref2;
var _useState = useState(getValue(props, [])),
_useState2 = _slicedToArray(_useState, 2),
value = _useState2[0],
setValue = _useState2[1];
var type = props.type,
block = props.block,
disabled = props.disabled,
iconAlign = props.iconAlign,
className = props.className,
style = props.style;
var _useContext = useContext(ConfigContext),
prefixCls = _useContext.prefixCls;
var bem = createBEM('checkbox-group', {
prefixCls: prefixCls
});
var cls = bem([(_ref2 = {}, _defineProperty(_ref2, "".concat(type), !!type), _defineProperty(_ref2, "block", block), _defineProperty(_ref2, "disabled", disabled), _ref2), className]);
useEffect(function () {
if (props.value === undefined) return;
if (isEqual(props.value, value)) return;
setValue(getValue(props, []));
}, [props.value]);
return /*#__PURE__*/React.createElement(CheckboxGroupContext.Provider, {
value: {
value: value,
type: type,
block: block,
disabled: disabled,
iconAlign: iconAlign,
check: function check(v) {
var _props$onChange;
var values = [].concat(_toConsumableArray(value), [v]);
setValue(values);
(_props$onChange = props.onChange) === null || _props$onChange === void 0 ? void 0 : _props$onChange.call(props, values);
},
uncheck: function uncheck(v) {
var _props$onChange2;
var values = value.filter(function (item) {
return item !== v;
});
setValue(values);
(_props$onChange2 = props.onChange) === null || _props$onChange2 === void 0 ? void 0 : _props$onChange2.call(props, values);
}
}
}, /*#__PURE__*/React.createElement("div", {
className: cls,
style: style
}, /*#__PURE__*/React.createElement("div", {
className: bem('inner')
}, type === 'list' ? /*#__PURE__*/React.createElement(List, null, props.children) : props.children)));
};
CheckboxGroup.displayName = 'CheckboxGroup';
CheckboxGroup.defaultProps = {
block: false,
disabled: false,
iconAlign: 'before'
};
export default CheckboxGroup;