[英]React Conditional rendering mapping an array
I have reproduced my scenario in this codesandbox我在这个代码沙盒中重现了我的场景
I have an array of tags of 5 elements我有 5 个元素的标签数组
const tagsList = ["Covid 19", "Business", "Energy", "Sport", "Politics"];
I am mapping for each tag my Chip
component我正在为每个标签映射我的
Chip
组件
{tagsList.map((tag) => (
<Chip label={tag} />
))}
I want to say that if the taglist length is bigger than 2 ( which is my case in the codesandbox ) to show me the chip with the tags left, which are 3 ( length - 2 ).我想说的是,如果 taglist 长度大于 2(这是我在codeandbox中的情况),则向我显示带有左侧标签的芯片,即 3(长度 - 2)。
How can i make in the same map function?我怎样才能在同一个地图功能中制作? Is there an other way?
还有其他方法吗?
You can use tagsList.slice(2)
if the list size is greater than 2.如果列表大小大于 2,您可以使用
tagsList.slice(2)
。
export default function OutlinedChips() {
const classes = useStyles();
const tagsList = ["Covid 19", "Business","Energy", "Sport", "Politics"];
return (
<div className={classes.root}>
{(tagsList.length > 2 ? tagsList.slice(2) : tagsList).map((tag) => (
<Chip label={tag} />
))}
</div>
);
}
Working code - https://codesandbox.io/s/material-demo-forked-31f2w?file=/demo.js工作代码 - https://codesandbox.io/s/material-demo-forked-31f2w?file=/demo.js
You can collect index (position of element in list) in the map function and act according to your needs, if I understand it wright mayby you could do something like this :您可以在 map 函数中收集索引(列表中元素的位置)并根据您的需要采取行动,如果我理解的话,您可以这样做:
return (
<div className={classes.root}>
{/* Change to shortTagsList for check the shortest */}
{tagsList.map((tag, index) => {
let length = tagsList.length;
console.log(length);
return (
(length > 2 && index > 2 && <Chip label={tag} />) ||
(length <= 2 && <Chip label={tag} />)
);
})}
</div>
);
You can do this if you don't mind not starting at position 0:如果您不介意不从位置 0 开始,您可以这样做:
<div className={classes.root}>
{(tagsList.length > 2 ? tagsList.slice(3, 5) : tagsList).map((tag) => (
<Chip label={tag} />
))}
{tagsList.length > 2 && <Chip label={tagsList.length - 2} /> }
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.