在反应应用中渲染DIV

时间:2018-03-22 09:24:18

标签: javascript html reactjs

喜。任务:

我从服务器获得一个包含帖子的数组。并归还:

{ this.state.articles.map((article) => {
return ( <div className={css(styles.feed_row)}>
  <div key={article.id} className={ css(boxes.art_box) }>
    <span className={css(boxes.cover)}>
      <img  src={article.art_cover} alt="" width={350}/>
    </span>
  </div>
</div> )
}

在出路的时候我会得到一个有很多帖子的div。

如何限制每个 .feed_row ,只有两个元素或已达到最大宽度,会自动创建一个新的 .feed_row 和继续添加帖子?

我想尝试这样的事情:

enter image description here

1 个答案:

答案 0 :(得分:1)

以下是如何将一维数组转换为所需的二维数组:

&#13;
&#13;
function articleRows(articles, max, maxWidth) {
  var rows = [];
  var currentRow = [];
  const fits = a => currentRow.reduce((acc, curr) => acc + curr.width, 0) + a.width <= maxWidth;
  articles.forEach(a => {
    if (currentRow.length < max && fits(a)) return currentRow.push(a);
    rows.push(currentRow);
    currentRow = [a];
  });
  rows.push(currentRow);
  return rows;
}

var articles = [];
for (var i = 0; i < 10; i++) {
  articles.push({
    width: Math.ceil(Math.random() * Math.random() * 4) * 150 + 150
  });
}

var rows = articleRows(articles, 2, 750);

console.log(articles.map(a => a.width));
console.log(rows.map(row => row.map(a => a.width).join(", ")));
&#13;
&#13;
&#13;

基本思路是创建一个空行数组,只要合适就推送到它,然后继续前进到下一行。

这是一个展示最终结果的React沙箱:{​​{3}}