React: Render new row every 4th column

前端 未结 7 1058
野的像风
野的像风 2020-12-30 03:55

I\'m using react and I want to render a new row every 4th column.

My code:

function Product(props) {
  const content = prop         


        
相关标签:
7条回答
  • 2020-12-30 04:38

    All of the current answers don't really seem Silly, Stupid as there focusing on just printing one set of items one time and not taking into account further processing of rows with differing amounts of items. The following answer uses typescript but could be simply implemented in vanilla JS. I'm also using lodash chunk as a convenience, though your own chunking method would be simple to add if required.

    import * as _ from 'lodash'
    
    export enum flexChunkOptions {
        col1 = 12,
        col2 = 6,
        col3 = 4,
        col4 = 3,
        col6 = 2,
        col12 = 1
    }
    
    
    export const chunkIntoFlexgrid = (numbOfItemsInRow: flexChunkOptions, arrayOfItems: ArrayLike<any>) => {
        return _.chunk(arrayOfItems, numbOfItemsInRow)
    }
    

    In the above we are creating an enum which has all of our bootstrap column definitions that are divisible by 12. This is done simply so we can use the corresponding col definition in our template for ease. We are expecting to receive an array of items of any type (note for ts users ArrayLike<any> is better for type safety than any). After which we return back a chunked down array probably something like [[1,2,3], [1,2,3]] if we choose col-3.

    const myArrOfItems = [1, 2, 3, 4, 5, 6, 7, 8]
    
    {chunkIntoFlexgrid(flexChunkOptions.col3, mySetOfItems).map((el, i) => {
                            return <div key={ `row-${ i }` } className={ `row` }>
                                {
                                    el.map(item => item)
                                }
                            </div>
                        })
    

    In our template we can simply call our connivence method and provide how we would like our rows to be generated and simply use our outer el variable to work with indvidual elements.

    Here's a link to the lodash chunk documentation

    0 讨论(0)
提交回复
热议问题