首页 > 解决方案 > 我们可以根据条件在 react.js 中的 map 中引入换行符(css)吗

问题描述

我有一个数组,我试图在数组的每四个元素中引入一个换行符,以便每四个元素在一起,而下一行将包含接下来的 4 个元素,依此类推。

this.state.colors: ['red', 'brown', 'yellow', 'blue', 'black', 'pink', 'green', 'aliceblue', 
'gray', 'magenta', 'orange', 'violet','coral', 'white', 'olive', 'lightgreen']

 <ul className="colorsList">
  {this.state.colors.map((color, index) => (
      <div>
          <div className="flex">
              <div style={{ background: color, height: 20, width: 20 }}></div>
          </div>
          {(index === 3 || 7 || 11) && <br></br>}
      </div>
  ))}
 </ul>

应该是这样的。。

[][][][]
[][][][]
[][][][]

这里的括号表示这些颜色框的高度和宽度为 20、20。

标签: javascriptreactjs

解决方案


我不想让 javascript 来解决我遇到的这个问题,并想用纯 CSS 来做。这是我的解决方案:)

this.state.colors: ['red', 'brown', 'yellow', 'blue', 'black', 'pink', 'green', 'aliceblue', 
'gray', 'magenta', 'orange', 'violet','coral', 'white', 'olive', 'lightgreen']

<ul className="colorsList">
                    {this.state.colors.map((color, index) => (
                        <div>
                            {(index % 4 === 0 ) ?
                                <div>
                                    <div style={{ clear: 'both' }}></div>
                                    <div style={{ background: color, height: 20, width: 20, float: 'left' }}></div>
                                </div>
                                :
                                <div style={{ background: color, height: 20, width: 20, float: 'left' }}></div>
                            }
                        </div>
                    ))}
                </ul>


推荐阅读