在渲染中反应 JS for 循环

React JS for loop inside rendering

我是 React JS 的新手,我不确定如何做一个 for 循环来渲染某些东西的次数可变。这是我的代码:

<div className="product-selector__products">
    { this.props.products.sort(function(a,b) { return a.ranking - b.ranking }).map((p) => { 

        const className = "product" + ((this.props.selectedProductIds.indexOf(p.id) !== -1) ? " product--selected" : "");
        const descriptionHtml = { __html: p.description };
        const nameHtml = { __html: p.name };

        return (
            <div className={className} key={ p.id } onClick={this.onProductClick.bind(this, p.id)}>

                <div className="product__image">
                    <img src={`/~/media/Bayer CropScience/Country-United-States-Internet/Comparison Tool/img/logos/${p.id}_sm.png`} alt={p.name} />
                </div>
                <div className="product__info">
                    <div className="product__name" dangerouslySetInnerHTML={nameHtml}></div>
                    <div className="product__description" dangerouslySetInnerHTML={descriptionHtml}></div>
                </div>
                <div className="product__message" ref={ p.id }>
                    <div className="product__message-tooltip">Please remove a product<br/>before adding another</div>
                    <div className="product__message-triangle-down"></div>
                </div>
            </div>     
        );  
    }) }

    /* Here I want to render <div className="product product--empty"> </div> a variable number of times*/

</div>

它生成一个产品项目网格,每行 4 个项目。

我需要在最后一行的末尾添加空的 divs,以便每行中的 divs 的数量相同。

所以如果 this.props.products.length == 7 我需要 1 个空的 div,如果我有 5 个产品我需要 3 个空的 div,等等

我想要的脚本是这样的:

let remainder = 4 - (this.props.products.length % 4);
  for (let i = 0; i < remainder; i++){
    return ( <div className="product product--empty"> </div> )
  }  

虽然我不确定如何将它正确地放入代码块中。

我刚刚修改了您的代码。

renderRemainders() {
  let products = []
  let remainder = 4 - (this.props.products.length % 4)

  for (let i = 0; i < remainder; i++){
    products.push( <div className="product product--empty"> </div> )
  }

  return products
}

然后把

 { this.renderRemainders() }

在您的 'render' 函数中的某处。

此外,您能否谈谈为什么需要呈现这些空行?