react.js every nth item add opening tag or closing tag

后端 未结 2 1182
深忆病人
深忆病人 2021-01-02 09:22

I\'m having trouble with this logic since react/jsx does not allow for non closing tags to be added to an array/child component. For example with bootstrap css I want to add

相关标签:
2条回答
  • 2021-01-02 09:47

    I actually just used arrays and react handled fine the rendering.

    render() {
        let rows = [],
            cols = []
        let index = 0
        const totalCols = 20;
    
        for (index; index < totalCols; index++) {
            cols.push(<div class="col" key={index}/>)
            if ((index + 1) % 4 == 0) {
                rows.push(
                    <div class="row" key={index}>
                        {cols}
                    </div>
                )
                cols = []
            }
        }
        return (
            <div class="container">
                {rows}
            </div>
        )
    }
    
    0 讨论(0)
  • 2021-01-02 10:08
    render() {
       const rows = array_chunk(this.props.columns, 4)
       return (
         {
           rows.map((row) => (
             <div className="row">
             {
               row.map((col) => (
                 <div className="col">{ col }</div>
               ))
             }
             </div>
           ))
         }
       )
    }
    

    An example array_chunk (I recommend that you use lodash)

    module.exports = function chunks(arr, size) {
      if (!Array.isArray(arr)) {
        throw new TypeError('Input should be Array');
      }
    
      if (typeof size !== 'number') {
        throw new TypeError('Size should be a Number');
      }
    
      var result = [];
      for (var i = 0; i < arr.length; i += size) {
        result.push(arr.slice(i, size + i));
      }
    
      return result;
    };
    
    0 讨论(0)
提交回复
热议问题