| 1 | /** |
| 2 | * Grid - 栅格布局组件 |
| 3 | * 用于替代 antd 的 Row/Col |
| 4 | */ |
| 5 | |
| 6 | 'use client' |
| 7 | |
| 8 | import * as React from 'react' |
| 9 | import { cn } from '@/utils/className' |
| 10 | |
| 11 | interface RowProps extends React.HTMLAttributes<HTMLDivElement> { |
| 12 | /** 栅格间隔 */ |
| 13 | gutter?: number | [number, number] |
| 14 | /** 子元素 */ |
| 15 | children?: React.ReactNode |
| 16 | } |
| 17 | |
| 18 | function Row({ gutter = 0, className, children, style, ...props }: RowProps) { |
| 19 | const [gutterX, gutterY] = Array.isArray(gutter) ? gutter : [gutter, gutter] |
| 20 | |
| 21 | return ( |
| 22 | <div |
| 23 | className={cn('flex flex-wrap', className)} |
| 24 | style={{ |
| 25 | marginLeft: gutterX ? `-${gutterX / 2}px` : undefined, |
| 26 | marginRight: gutterX ? `-${gutterX / 2}px` : undefined, |
| 27 | marginTop: gutterY ? `-${gutterY / 2}px` : undefined, |
| 28 | marginBottom: gutterY ? `-${gutterY / 2}px` : undefined, |
| 29 | ...style, |
| 30 | }} |
| 31 | {...props} |
| 32 | > |
| 33 | {React.Children.map(children, (child) => { |
| 34 | if (React.isValidElement(child)) { |
| 35 | return React.cloneElement(child, { |
| 36 | style: { |
| 37 | paddingLeft: gutterX ? `${gutterX / 2}px` : undefined, |
| 38 | paddingRight: gutterX ? `${gutterX / 2}px` : undefined, |
| 39 | paddingTop: gutterY ? `${gutterY / 2}px` : undefined, |
| 40 | paddingBottom: gutterY ? `${gutterY / 2}px` : undefined, |
| 41 | ...(child.props.style || {}), |
| 42 | }, |
| 43 | } as any) |
| 44 | } |
| 45 | return child |
| 46 | })} |
| 47 | </div> |
| 48 | ) |
| 49 | } |
| 50 | |
| 51 | interface ColProps extends React.HTMLAttributes<HTMLDivElement> { |
| 52 | /** 栅格占位格数,为 0 时不占位 */ |
| 53 | span?: number |
| 54 | /** 子元素 */ |
| 55 | children?: React.ReactNode |
| 56 | } |
| 57 | |
| 58 | function Col({ span = 24, className, children, style, ...props }: ColProps) { |
| 59 | // 将 antd 的 24 栅格系统转换为百分比 |
| 60 | const widthPercent = (span / 24) * 100 |
| 61 | |
| 62 | return ( |
| 63 | <div |
| 64 | className={cn('flex-shrink-0', className)} |
| 65 | style={{ |
| 66 | width: `${widthPercent}%`, |
| 67 | ...style, |
| 68 | }} |
| 69 | {...props} |
| 70 | > |
| 71 | {children} |
| 72 | </div> |
| 73 | ) |
| 74 | } |
| 75 | |
| 76 | export { Col, Row } |
| 77 |