All files / src/components/Col index.js

0% Statements 0/26
0% Branches 0/8
0% Functions 0/3
0% Lines 0/25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96                                                                                                                                                                                               
/**
 * @Component Col
 * @Type 布局组件
 * @Author 瞿龙俊 - qulongjun@shine.design
 * @Date 2019-03-24 12:43
 */
import React, {PureComponent} from 'react';
import _ from 'lodash';
import classNames from 'classnames';
import * as PropTypes from 'prop-types';
import {classPrefix} from '../../_variables';
import './style/index.scss';
 
class Col extends PureComponent {
  constructor(props) {
    super(props);
 
    this.onColClasses = this.onColClasses.bind(this);
  }
 
  /**
   * 若 param 属性为数字类型,则直接生成 param-xxx 修饰符,如 col-3,offset-3,order-3
   * 若 param 属性为对象,则生成 param-key-value 修饰符,如 col-md-3,offset-md-3,order-md-3
   * 特殊的,如果 key 为 default ,则依然生成 param-xxx 修饰符,如 col-3,offset-3,order-3
   * @return Array Col 修饰符
   */
  onColClasses(param) {
    const data = this.props[param];
 
    if (_.isNumber(data) || _.isString(data)) {
      return [`${classPrefix}-${param}-${data}`];
    }
 
    const colClasses = [];
    if (_.isObject(data)) {
      _.forIn(data, (value, key) => {
        colClasses.push(_.isEqual(key, 'default') ? `${classPrefix}-${param}-${value}` : `${classPrefix}-${param}-${key}-${value}`);
      });
    }
 
    return colClasses;
  }
 
 
  render() {
    const {className, attributes, children} = this.props;
    const special = ['col', 'offset', 'order'];
    /** 计算样式 */
    const classes = classNames(
      _.flatten(_.map(special, item => this.onColClasses(item))),
      className,
    );
    return (
      <div
        className={classes}
        {...attributes}
      >
        {children}
      </div>
    );
  }
}
 
Col.propTypes = {
  /** 定义列格块数 */
  col: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string,
    PropTypes.object,
  ]),
  /** 定义列格块偏移量 */
  offset: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.object,
  ]),
  /** 定义列格块排列顺序 */
  order: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.object,
  ]),
  /** 用户自定义修饰符 */
  className: PropTypes.string,
  /** 用户自定义属性 */
  attributes: PropTypes.object,
};
 
Col.defaultProps = {
  col: 'auto',
  offset: undefined,
  order: undefined,
  className: '',
  attributes: {},
};
 
export default Col;