与this question相关,我有一些项目,我想在React js中对其进行迭代。这是我的物品和组件:
const itemlists = [
{
"id": 1,
"url": "/one",
"title": "One",
"category": "News"
},
{
"id": 2,
"url": "/two",
"title": "Two",
"category": "News"
},
{
"id": 3,
"url": "/three",
"title": "Three",
"category": "News"
},
{
"id": 4,
"url": "/four",
"title": "Four",
"category": "News"
},
{
"id": 5,
"url": "/five",
"title": "Five",
"category": "News"
},
{
"id": 6,
"url": "/six",
"title": "Six",
"category": "News"
}
]
卡组件
class Cards extends Component {
render() {
const renderData = itemlists.map((item, i) => {
return (
<div className="card-row" key={i}>
<div className="card-content">
<div className="card-left">
// This should be 2 items in left side
<div className="item">{item.title}</div>
</div>
<div className="card-right">
// This should be 4 items in right side
<div className="item">{item.title}</div>
</div>
</div>
<div className="pagination">
<a href={item.url}>More in {item.category}</a>
</div>
</div>
)
})
return (
<Fragment>
{renderData}
</Fragment>
);
}
}
将
if else statement
放入return
时出现解析错误,例如:<div className="card-left">
{
---- this if statement gives error ----
if((items + 1) % 3 === 0) {
....
}
}
<div className="item">{item.title}</div>
</div>
我的目标是将这些项目分为两组(左侧2个,右侧4个)。我也想在
<div className="pagination">
中放置分页链接。我一直在混淆逻辑。让我知道是否有实现目标的简单方法。问候。
最佳答案
代替if-else
语句,使用ternary operator像这样:
(items + 1) % 3 === 0 ? doThis() : doThat()
关于javascript - 如何在React js中进行迭代并将其分为两组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51721162/