Grid组件
Row
import React from 'react';
import { Children, cloneElement } from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
export interface RowProps {
className?: string;
gutter?: number;
type?: 'flex';
align?: 'top' | 'middle' | 'bottom';
justify?: 'start' | 'end' | 'center' | 'space-around' | 'space-between';
style?: React.CSSProperties;
prefixCls?: string;
}
export default class Row extends React.Component<RowProps, {}> {
static defaultProps = {
gutter: 0,
};
static propTypes = {
type: PropTypes.string,
align: PropTypes.string,
justify: PropTypes.string,
className: PropTypes.string,
children: PropTypes.node,
gutter: PropTypes.number,
prefixCls: PropTypes.string,
};
render() {
const { type, justify, align, className, gutter, style, children,
prefixCls = 'ant-row', ...others } = this.props;
const classes = classNames({
[prefixCls]: !type,
[`${prefixCls}-${type}`]: type,
[`${prefixCls}-${type}-${justify}`]: type && justify,
[`${prefixCls}-${type}-${align}`]: type && align,
}, className);
// 如果有gutter这个参数,就是需要添加间距,他的实现方法是给每一个Item添加左右的pading,
// 但是又不想让第一个和最后一个Item也有这个内边距,所以在父级元素上面设置左右相同负值
// 的margin,就能够抵消两端的padding。
const rowStyle = (gutter as number) > 0 ? {
marginLeft: (gutter as number) / -2,
marginRight: (gutter as number) / -2,
...style,
} : style;
// 这里就用到了上面所说的Children 和 cloneElement
// React.Children使用的时候不必担心内部子元素是否有嵌套关系
const cols = Children.map(children, (col: React.ReactElement<HTMLDivElement>) => {
if (!col) {
return null;
}
// 判断一下col是否有props
if (col.props && (gutter as number) > 0) {
// 返回一个新的组件,会新增添加的其余的props或者修改过后的props
return cloneElement(col, {
style: {
paddingLeft: (gutter as number) / 2,
paddingRight: (gutter as number) / 2,
...col.props.style,
},
});
}
return col;
});
return <div {...others} className={classes} style={rowStyle}>{cols}</div>;
}
}Col
Last updated