如何在div ReactJS中将JSON中的数据显示为flex行



这是我的代码。我想在div中将JSON文件中的数据显示为flex行。但我得到的是列。我用顺风把它显示为柔性行。以下是预期输出:https://i.stack.imgur.com/f8uAp.jpg

import React, { Component } from "react";
import PostData from "../data/data.json";
class Sneaker extends Component {
state = {};
render() {
return (
<div>
{PostData.map((postDetail) => {
return (
<div className="flex flex-row bg-gray-400 w-2/3 mx-auto mt-10">
<div className="text-center w-1/4 p-2 m-2 bg-white">
<img className="w-64 h-64" src={postDetail.image} alt="" />
<h1>{postDetail.name}</h1>
<h1 className="text-red-500">${postDetail.price}</h1>
</div>
</div>
);
})}
</div>
);
}
}
export default Sneaker;

尝试将postData循环放入flex行div中,如下所示

<div className="flex flex-row bg-gray-400 w-2/3 mx-auto mt-10">
{PostData.map((postDetail) => {
return (                
<div className="text-center w-1/4 p-2 m-2 bg-white">
<img className="w-64 h-64" src={postDetail.image} alt="" />
<h1>{postDetail.name}</h1>
<h1 className="text-red-500">${postDetail.price}</h1>
</div>
);
})}
</div>

如果你想把3个项目放在一个flex行中,你可以写这样的代码:

import React, { Component } from "react";
import PostData from "../data/data.json";
const perRow = 3;
class Sneaker extends Component {
state = {};
render() {
return (
<div>
{PostData.map((ignoreIt, i) => {
return i % perRow === 0 ? (
<div
className="flex flex-row bg-gray-400 w-2/3 mx-auto mt-10"
key={i}
>
{PostData.slice(i, i + perRow).map((postDetail, j) => {
return (
<div
className="text-center w-1/4 p-2 m-2 bg-white"
key={i + j}
>
<img className="w-64 h-64" src={postDetail.image} alt="" />
<h1>{postDetail.name}</h1>
<h1>{j}</h1>
<h1 className="text-red-500">${postDetail.price}</h1>
</div>
);
})}
</div>
) : null;
})}
</div>
);
}
}
export default Sneaker;

相关内容

  • 没有找到相关文章