javascript - 为来自 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;
我该如何继续?
解决方案
将此添加到您的 css 文件中。
有关更多信息,请参阅 https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout
.item_list_main {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
这意味着对于一行,您的列将包含四个片段。
推荐阅读
- javascript - 从函数返回的数组解构中的花括号
- sql - 创建动态列
- python - 通过websocket python发送特殊字符时出错 Hele me?
- python - 期望与 pexpect 等效的解释器
- javascript - 限制用户只能输入英文文本输入,反应原生时没有其他语言
- c++ - 声明和使用大小为 n 的数组与声明和使用 n 个变量
- javascript - 检查密码后重定向页面
- javascript - 如何使用 TensorFlow.js 预测有害词
- java - 使用从数据库中提取的数据填充 Android Listview
- css - 在一个标签的末尾落在一个标签的中间