Moe*_*Moe 3 javascript css reactjs material-ui
使用 MUI V5,如何将自定义样式传递给按钮组件?这是我一直在尝试将旧方法与新 MUI v5 合并的方法,但它不起作用。
import { Button } from "@mui/material";
import { styled } from "@mui/material/styles";
import React from "react";
const StyledButton = styled(Button)(({ theme }) => ({
root: {
minWidth: 0,
margin: theme.spacing(0.5),
},
secondary: {
backgroundColor: theme.palette.secondary.light,
"& .MuiButton-label": {
color: theme.palette.secondary.main,
},
},
primary: {
backgroundColor: theme.palette.primary.light,
"& .MuiButton-label": {
color: theme.palette.primary.main,
},
},
}));
export default function ActionButton(props) {
const { color, children, onClick } = props;
return (
<Button
className={`${StyledButton["root"]} ${StyledButton[color]}`}
onClick={onClick}
>
{children}
</Button>
);
}
Run Code Online (Sandbox Code Playgroud)
现在我想调用这个按钮并给它 color=“secondary”
import ActionButton from "./ActionButton";
import { Close } from "@mui/icons-material";
export default function Header() {
return (
<ActionButton color="secondary">
<Close />
</ActionButton>
)
}
Run Code Online (Sandbox Code Playgroud)
看起来您的代码是尝试使用 迁移代码makeStyles/useStyles,但styled工作方式有很大不同。您不能使用它来生成多个 CSS 类,如makeStylesdoes (StyledButton["root"]和StyledButton[color]will be undefined)。styled将生成一个 CSS 类,然后将其在classNameprop 中传递给包装组件(例如Button)。styled您可以利用 props(例如colorprop)在生成的单个 CSS 类中生成动态样式,而不是尝试创建多个 CSS 类并通过逻辑来决定应用哪个类。
下面是一个我认为可以达到您的代码想要的效果的示例。我的示例没有执行任何操作MuiButton-label,因为该类在 v5 中不存在(并且该类在 v4 中<span>应用到的内部也不<button存在),并且我相信当prop为允许通过到.colorcolorButton
import Button from "@mui/material/Button";
import { styled } from "@mui/material/styles";
const StyledButton = styled(Button)(({ theme, color }) => ({
minWidth: 0,
margin: theme.spacing(0.5),
backgroundColor: color ? theme.palette[color].light : undefined
}));
export default StyledButton;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3146 次 |
| 最近记录: |