首页 > 解决方案 > 为来自 API 调用的数据创建动态网格(行和列)

问题描述

我对 React JS 和 JavaScript 完全陌生。我正在通过制作小项目来练习。我无法制作动态行和列。这样我就可以有 4 列数据和第 5 列数据,它应该创建新的行和列,并且应该一直持续到数据结束。

例如

在此处输入图像描述

下面是代码

import React, { Component } from 'react';
import './itemslist.css';
import axios from 'axios';
import { Link } from 'react-router-dom';



class ItemsList extends Component{

  constructor(props){
  super(props);
  this.state = {
    productList: []
  }
  }

  async componentDidMount(){
    const homeAPI = `${window.apiHost}/api/items/`;
    await axios.get(homeAPI).then(res => {
      this.setState({productList: res.data.result.product_data})
    })
  }

  render(){

//this where i am not able to make row and col.

    const products = this.state.productList.map((product, i)=>{
      return(

          <div className="card text-center card_style" key={i} style={{marginBottom: '120px'}}>
            <div className="card-header">
              {product.name}
            </div>
            <Link to={`/items/${product.id}`}>
              <img className="card-img-top card_image" src={product.image} alt="Card"/>
            </Link>
            <div className="card-footer text-muted">
              <p className="card-text">{product.description}</p>
              {product.price}
            </div>
          </div>

      )
    }
  )
    return(
      <div className="item_list_main">
        {products}
      </div>
    )
  }
}


export default ItemsList;

我该如何继续?

标签: javascripthtmlcssreactjsbootstrap-4

解决方案


将此添加到您的 css 文件中。

有关更多信息,请参阅 https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

.item_list_main {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}

这意味着对于一行,您的列将包含四个片段。


推荐阅读