jsx import { Interpolation , jsx , Theme } from "@emotion/react" ; import React , { useCallback } from "react" ; import CSS from "csstype" ; import { style } from "./style" ; import { normalizeUnit } from "../utils/cssUtil" ; export interface AutoGridOption extends React . HTMLProps < HTMLDivElement > { children ? : React . ReactNode ; containerStyle ? : Interpolation < Theme > ; gap ? : CSS . Property . Width ; cols ? : number ; isSquare ? : boolean ; itemStyle ? : Interpolation < Theme > ; } param props export function AutoGrid ( props ) { let { children , cols = 1 , gap = 0 , isSquare = false , itemStyle , containerStyle , ... extra } = props ; cols = + cols ; gap = normalizeUnit ( gap ) as string ; const getGridData = useCallback ( ( ) => { let list = [ ] ; React . Children . forEach ( children , ( child ) => { if ( child !== null ) { if ( list . length === 0 || list [ list . length - 1 ] . length >= cols ) { list . push ( [ ] ) ; } list [ list . length - 1 ] . push ( child ) ; } } ) ; return list ; } , [ children ] ) ; const finalItemBoxStyle = [ style . itemBoxStyle , { marginRight : gap , width : `calc((100% - ${ cols - 1 } * ${ gap }) / ${ cols })` , } , ] ; /**
     * 显示内容
     */ const showContent = ( ) => { const gridData = getGridData ( ) ; return gridData . map ( ( row , rowIndex ) => { let finalRowStyle = [ style . rowStyle ] ; if ( rowIndex !== gridData . length - 1 ) { finalRowStyle . push ( { marginBottom : gap , } ) ; } return ( < div key = { rowIndex } css = { finalRowStyle } > { row . map ( ( item , colIndex ) => { let finalCss = [ ... finalItemBoxStyle ] ; if ( isSquare ) { finalCss . push ( style . itemBoxSquare ) ; } finalCss . push ( itemStyle ) ; if ( isSquare ) { return ( < div css = { finalCss } key = { colIndex } > < div css = { style . itemInnerStyle } > { item } < /div> < /div>); } else { return ( < div css = { finalItemBoxStyle } key = { colIndex } > { item } < /div>); } } ) } < /div>); } ) ; } ; return ( < div { ... extra } css = { [ containerStyle ] } > { showContent ( ) } < /div>); }