【问题标题】:Create dynamic grid (row and col) for data coming from API call为来自 API 调用的数据创建动态网格(行和列)
【发布时间】:2020-05-19 22:47:54
【问题描述】:

我对 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;

我该如何继续?

【问题讨论】:

  • 你能添加你的css文件吗?到目前为止,您尝试过什么包装产品?
  • @chandan_kr_jha 我尝试过使用 CSS 但无法做到。我试图包装产品,但我也失败了。
  • 你必须使用flexbox或grid。
  • @chandan_kr_jha 我可以使用网格制作该行和列,但动态制作它是我无法做到的。

标签: javascript html css reactjs bootstrap-4


【解决方案1】:

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

更多请参考 https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

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

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

【讨论】:

    【解决方案2】:

    @Milan_Thapa。您可以使用宽度:25%;在每个组件中。 但是假设组件大小可以不同。宽度和高度可以有很大的不同。

    最好的选择是使用在这种情况下非常流行的 Masonry。

    https://masonry.desandro.com/

    希望这行得通。

    【讨论】:

    • 我会试试这个。
    猜你喜欢
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多