【发布时间】:2021-10-14 12:28:21
【问题描述】:
我正在尝试根据类别更改每个头像背景颜色,例如,如果类别是“工作”,那么头像颜色必须是黄色 如果类别是“待办事项”,那么头像颜色必须是粉红色和很快。但是代码显示每个头像的默认灰色背景颜色。我无法更改背景颜色。
import React from "react";
import Card from "@mui/material/Card";
import CardHeader from "@mui/material/CardHeader";
import CardContent from "@mui/material/CardContent";
import { IconButton, Typography } from "@mui/material";
import { DeleteOutlined } from "@mui/icons-material";
import { makeStyles } from "@mui/styles";
import { blue, green, pink, yellow } from "@mui/material/colors";
import Avatar from "@mui/material/Avatar";
const useStyles = makeStyles({
avatar: {
backgroundColor: (note) => {
if (note.category == "work") {
return yellow[700];
}
if (note.category == "money") {
return green[500];
}
if (note.category == "todos") {
return pink[500];
}
return blue[500];
},
},
});
const NoteCard = ({ note, handleDelete }) => {
const classes = useStyles(note);
return (
<div>
<Card elevation={1}>
<CardHeader
avatar={
<Avatar className={classes.avatar}>
{note.category[0].toUpperCase()}
</Avatar>
}
action={
<IconButton onClick={() => handleDelete(note.id)}>
<DeleteOutlined />
</IconButton>
}
title={note.title}
subheader={note.category}
/>
<CardContent>
<Typography variant="body2" color="textSecondary">
{note.details}
</Typography>
</CardContent>
</Card>
</div>
);
};
export default NoteCard;
【问题讨论】:
-
无论如何,您都应该在 MUI v5 中使用
styled函数而不是makeStyles。makeStyles是旧版 API,在新版本中不推荐使用,可能会在 v6 中移除。
标签: reactjs material-ui