gpt4 book ai didi

javascript - 如何在 react 组件中以不同形式显示数组的每个部分

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:08:05 25 4
gpt4 key购买 nike

我要实现一个在框中显示数据的组件。每一个常数的数据都应该放在一个div中返回。

我有一个显示数据的 Box 组件。在 Tutorial 组件中,我们有包含数据数组的 Prop :

//Box component
import React from 'react'
import { Link } from 'react-router-dom'

const Box = ({ item, index}) => {
return (
<div key={index}>
<div className="tutorial">
<img src={item.imgLink} className="resp-img" alt="Tutorial" />
<div className="tutorial-details">
<h6>{item.title}</h6>
<p><span className="lessons">
<i className="zmdi zmdi-assignment"></i>{item.shortDesc}</span><span className="duration"><i className="zmdi zmdi-time"></i>{item.duration}</span></p>
<p className="abs">{item.desc}</p>
<Link to={item.link} className="greybutton">VIEW COURSE</Link>
</div>
</div>
</div>
);
}

export default Box;


//Tutorial Component
import React from 'react'
import Box from './Box'

const Tutorials = ({ props, columnNumbers = 3 }) => {
return (
<>
{
props.map((item, index) => {
return (
// ????
)})
}
</>

)
}
export default Tutorials;

我应该如何在教程中映射 Prop 以获得结果?

<div className="row">
<Box item={item} index={index} ></Box>
<Box item={item} index={index} ></Box>
<Box item={item} index={index} ></Box>
</div>
<div className="row">
<Box item={item} index={index} ></Box>
<Box item={item} index={index} ></Box>
<Box item={item} index={index} ></Box>
</div>
<div className="row">
<Box item={item} index={index} ></Box>
<Box item={item} index={index} ></Box>
<Box item={item} index={index} ></Box>
</div>

最佳答案

您需要chunk项目,然后将它们映射到框。

chunk: Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements.

Note: check chunk implementation, the example uses lodash.chunk.

_.chunk(items, columnNumbers).map((itemGroup,index) => (
<div className="row" key={index}>
{itemGroup.map(item => (
<Box key={item.id} item={item.data} index={item.index} />
))}
</div>
));

可能的教程实现:

const Tutorials = ({ items, columnNumbers }) => (
<>
{chunk(items, columnNumbers).map((itemGroup, index) => (
<div className="row" key={index}>
{itemGroup.map(item => (
<Box key={item.id} item={item.data} index={item.index} />
))}
</div>
))}
</>
);

Tutorials.defaultProps = {
columnNumbers: 3
}

export default Tutorials;

关于javascript - 如何在 react 组件中以不同形式显示数组的每个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57958842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com