React 条件渲染映射数组

我在这个codesandbox中重现了我的场景


我有一个包含 5 个元素的标签数组


const tagsList = ["Covid 19", "Business", "Energy", "Sport", "Politics"];

我正在为我的Chip组件的每个标签进行映射


  {tagsList.map((tag) => (

    <Chip label={tag} />

  ))}

我想说的是,如果标签列表长度大于2(这是我在codesandbox中的情况),则向我显示带有剩余标签的芯片,即3(长度-2)。


我怎样才能在同一个地图功能中制作?还有其他办法吗?


万千封印
浏览 156回答 3
3回答

慕娘9325324

tagsList.slice(2)如果列表大小大于 2,则可以使用。export default function OutlinedChips() {&nbsp; const classes = useStyles();&nbsp; const tagsList = ["Covid 19", "Business","Energy", "Sport", "Politics"];&nbsp; return (&nbsp; &nbsp; <div className={classes.root}>&nbsp; &nbsp; &nbsp; {(tagsList.length > 2 ? tagsList.slice(2) : tagsList).map((tag) => (&nbsp; &nbsp; &nbsp; &nbsp; <Chip label={tag} />&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; </div>&nbsp; );}工作代码 - https://codesandbox.io/s/material-demo-forked-31f2w?file=/demo.js

郎朗坤

如果你不介意不从位置 0 开始,你可以这样做:<div className={classes.root}>&nbsp; &nbsp; &nbsp; {(tagsList.length > 2 ? tagsList.slice(3, 5) : tagsList).map((tag) => (&nbsp; &nbsp; &nbsp; &nbsp; <Chip label={tag} />&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; {tagsList.length > 2 && <Chip label={tagsList.length - 2} /> }</div>

至尊宝的传说

您可以在映射函数中收集索引(列表中元素的位置)并根据您的需要进行操作,如果我理解正确的话,您可以执行以下操作:return (&nbsp; &nbsp; <div className={classes.root}>&nbsp; &nbsp; &nbsp; {/* Change to shortTagsList for check the shortest */}&nbsp; &nbsp; &nbsp; {tagsList.map((tag, index) => {&nbsp; &nbsp; &nbsp; &nbsp; let length = tagsList.length;&nbsp; &nbsp; &nbsp; &nbsp; console.log(length);&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (length > 2 && index > 2 && <Chip label={tag} />) ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (length <= 2 && <Chip label={tag} />)&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; })}&nbsp; &nbsp; </div>&nbsp; );代码沙盒
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript