如何使用React和Material UI网格制作两列,只需迭代一个映射



我正在使用材质UI网格。我要做的是在两列中显示从map函数迭代得到的信息。但是,目前它只显示在1列中。作为测试,我添加了另一个网格项sm={6},并使用了相同的映射函数。实现了两列,但是两列显示的信息完全相同。我的问题是,当只有一个映射函数可以迭代时,如何将网格分解为两列?

const renderData = (person, picture, index) => {
return (
<Paper className={classes.Paper}>
<img src={person.picture.large} />
</Paper>
)
}
return (
<div className={classes.sectionContainer}>
<h3 className={classes.title}>Follow our instagram!</h3>
<h3 className={classes.title}>@platformdanceshowcase</h3>
<Grid direction='row' container spacing={1}>
<Grid item sm={6}>
{previewData.slice(0, visible).map(renderData)}
</Grid>
</Grid>
<Container className={classes.extendButtonArea}>
{visible < previewData.length && (
<Button className={classes.extendButton} onClick={loadMore}>
View More...
</Button>
)}
</Container>
</div>
)
}

如能提供任何帮助,我们将不胜感激。我绕了一圈,让自己更加困惑,所以提前感谢你!

很难从这个问题中准确地说出你想要做什么,也许你可以标记一个屏幕截图,或者提供一个你想要实现的目标的草图?

我真的不知道为什么renderData组件中有两个返回函数,但我将第一个解释为previewData数组的元素代表,第二个解释为您在问题中描述的columns元素。

我对您的问题的解释是,您希望两列并排呈现previewData中的数据。数据从索引0到可见。实现这一点的一种方法可能是这样修改代码:

<Grid direction='row' container spacing={1}>
<Grid container item sm={6}>
{previewData.slice(0, visible).map((renderData, i) => 
i % 2 == 0 ? renderData : <></>)}
</Grid>
<Grid container item sm={6}>
{previewData.slice(0, visible).map((renderData, i) => 
i % 2 == 1 ? renderData : <></>)}
</Grid>
</Grid>

map函数提供了与索引相对应的第二个参数,因此可以使用该参数在列之间分布元素。你也可以很容易地重新配置它,在左边显示你的前半部分,在右边显示你的后半部分。

<Grid direction='row' container spacing={1}>
<Grid container item sm={6}>
{previewData.slice(0, Math.Floor(visible / 2)).map(renderData)}
</Grid>
<Grid container item sm={6}>
{previewData.slice(Math.Ceil(visible / 2), visible).map(renderData)}
</Grid>
</Grid>

最新更新