与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">
中。我一直在混淆逻辑。让我知道是否有简单的方法可以实现我的目标。
致谢。
答案 0 :(得分:3)
使用ternary operator代替if-else
语句,
(items + 1) % 3 === 0 ? doThis() : doThat()
答案 1 :(得分:0)