首页 > 解决方案 > React with Material UI 模板中索引的某些图标

问题描述

我正在尝试使用if,因为我想为每个添加一个图标,ListItem但 React 不允许我这样做,我应该怎么做?我应该改变什么吗?提前致谢。

   <List>
      {["Inbox", "Starred", "Send email", "Drafts"].map((text, index) => (
        <ListItem button key={text}>
          <ListItemIcon>
            {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
          </ListItemIcon>
          <ListItemText primary={text} />
        </ListItem>
      ))}
   </List>

我尝试使用它,但它没有用:

<ListItemIcon>
   {index === 0 <InboxIcon/>}
   {index === 1 <MailIcon/>}
   {index === 2 <DeleteForeverOutlinedIcon />}
   {index === 3 <DeleteTwoToneIcon />}
</ListItemIcon>

标签: reactjsmaterial-ui

解决方案


您的&&代码中缺少 。你应该写类似

<ListItemIcon>
   {index === 0 && <InboxIcon/>}
   {index === 1 && <MailIcon/>}
   {index === 2 && <DeleteForeverOutlinedIcon />}
   {index === 3 && <DeleteTwoToneIcon />}
</ListItemIcon>


推荐阅读