https://codesandbox.io/s/r546o8v0kq
我上面的沙箱显示了项目数组的基本映射。这会根据项目的类型形成一个注释、日期和图标列表。
我正在处理一些逻辑来映射每个项目以找出它的值,基于此我为该值分配一个字符串以完成 Font Awesome Logo 的类型。
const noteType = _.uniq(notes.map(value => value.intelType));
const noteIcon = [
`${noteType}`.toUpperCase() == "EDUCATION"
? "paper-plane"
: `${noteType}`.toUpperCase() == "ELIGIBILITY"
? "heart"
: `${noteType}`.toUpperCase() == "GENERAL"
? "twitter"
: null
];
如果“intelType”的值为“education”,它将返回“paper-plane”字符串来完成图标。例如 fa fa-${noteIcon}
<List>
{notes.map((note, index) =>
note !== "" ? (
<React.Fragment>
<ListItem className="pl-0">
<i class={`fa fa-${noteIcon}`} aria-hidden="true" />
<ListItemText
secondary={moment(note.createdAt).format("DD-MMM-YYYY")}
/>
</ListItem>
<p>{note.note}</p>
<Divider />
</React.Fragment>
) : null
)}
</List>
它没有被映射并返回所有三个值,这不符合任何条件,因此按要求返回 null。我有点不知道接下来要做什么。
最佳答案
您可以定义一个将英特尔类型映射到图标名称的对象:
const noteIconMap =
{ "EDUCATION": "paper-plane",
"ELIGIBILITY": "heart",
"GENERAL": "twitter",
};
并在渲染中以这种方式查找:
<i class={`fa fa-${noteIconMap[note.intelType.toUpperCase()]}`} aria-hidden="true" />
尽管如此,请注意,如果存在 note
可以未定义 intelType
的情况,toUpperCase
调用将引发错误。
这是一个链接到工作修改后的沙箱: https://codesandbox.io/s/ojz2lzz03z
关于javascript - 根据 React 中的属性值映射不同的图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53727103/