[英]reactjs iterating over an array and placing wrapper divs every nth element
我在反应中使用材料 ui 网格系统。 我有一个 json 对象 -- 并且希望每 4 个元素创建一行。 所以它每 4 个元素包装容器 - 也能够控制第 n 个元素包装 - 所以如果他们想要连续每 2、3 个元素配置它。
像这样的东西
let blogJson = [{
"label" : "Dress up or down",
"body" : "<p>xxx</p>",
"image" : "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcS1q3hgINIvT2lxrLXVMoDlHt92bjqmU9SPHQ&usqp=CAU"
},{
"label" : "yyyyyyy",
"body" : "<p>xxx</p>",
"image" : "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcS1q3hgINIvT2lxrLXVMoDlHt92bjqmU9SPHQ&usqp=CAU"
},{
"label" : "nnnnnnnnnnn",
"body" : "<p>xxx</p>",
"image" : "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcS1q3hgINIvT2lxrLXVMoDlHt92bjqmU9SPHQ&usqp=CAU"
},{
"label" : "vvvvvvvvvv",
"body" : "<p>xxx</p>",
"image" : "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcS1q3hgINIvT2lxrLXVMoDlHt92bjqmU9SPHQ&usqp=CAU"
}]
{
blogJson.map((item, j) => {
return(
{j % 4 === 0? '<Grid container spacing={1}>'}
<Grid key={j} item xs={12} sm={3}>
<Card className="blog-card">
<CardContent>
<img src={item.image} alt="" />
<h3>{item.label}</h3>
{item.body}
</CardContent>
<CardActions>
<IconButton aria-label="add to favorites">
<FavoriteIcon className="icon-heart" />
</IconButton>
</CardActions>
</Card>
</Grid>
{j % 4 === 0? '</Grid>'}
)
})
}
将列表切成子列表并映射它们。
这是一个整洁的mapInSlices
助手。
const posts = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; function mapInSlices(array, sliceSize, sliceFunc) { const out = []; for (var i = 0; i < array.length; i += sliceSize) { const slice = array.slice(i, i + sliceSize); out.push(sliceFunc(slice, i)); } return out; } const App = () => ( <main> {mapInSlices(posts, 4, (slice) => ( <div> {slice.map((post) => ( <span>{post}</span> ))} </div> ))} </main> ); ReactDOM.render(<App />, document.getElementById("root"));
div { border: 1px solid orange; padding: .5em; margin: .5em; } span { margin: 1em; padding: .5em; background: cyan; display: inline-block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script> <main id="root"></main>
你可以使用React.createElement
来实现这一点
{
blogJson.map((item, j) => {
return React.createElement(
j % 4 === 0 ? Grid : React.Fragment,
j % 4 === 0 ? { container: true, spacing: 1 } : {},
<Grid key={j} item xs={12} sm={3}>
<Card className="blog-card">
<CardContent>
<img src={item.image} alt="" />
<h3>{item.label}</h3>
{item.body}
</CardContent>
<CardActions>
<IconButton aria-label="add to favorites">
<FavoriteIcon className="icon-heart" />
</IconButton>
</CardActions>
</Card>
</Grid>
)
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.