[英]How to wrap JSX elements in a single div when using .map() with React?
[英]React how to wrap each 3 elements in a div?
此處預期的 output 應該是藍色 div 內的每個 3 div(紅色)。 我不明白我做錯了什么,因為這通常應該有效。
// tried this method, https://stackoverflow.com/questions/63695426/react-wrap-every-3-components-into-a-div can't get it to work. 🤷♂️
const ImageGrid = ({slice} :any) => (
slice?.items?.map((item :any, i:number) => {
const myArrx :any = []
myArrx.push(<Box bg={'red'} p={15}><img src={item.image.url} alt={item.image.alt} /></Box>)
return myArrx.reduce((groups :any, curr:any) => {
const arr : any[] = groups[groups.length - 1];
arr.push(curr);
if (arr.length === 3) groups.push([]);
return <Box bg={'blue'} p={15}>{groups}</Box>;
}, [[]])
})
)
我正在努力做到這一點,這是簡單而優雅的解決方案
const ImageGrid = ({slice} :any) => {
const pack :any = []
slice?.items?.map((item :any, i:number) => {
pack.push(<Child data={item}/>)
})
const data2 = [...pack]
const groupedData1 = []
while(data2.length) {
groupedData1.push(data2.splice(0, 3));
}
return (
<>
<Container maxW={1180} bg='orange'>
<GridWrap>
{groupedData1.map((el, i) =>
<Parent>
<HStack alignItems={'top'}> {el} </HStack>
</Parent>
)}
</GridWrap>
</Container>
</>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.