[英]How to use conditional styles with MUI v5 using emotion styled
I'm migrating from MUI v4 to v5.我正在从 MUI v4 迁移到 v5。 In v4 I was using
clsx
with TextField
to add conditional styles.在 v4 中,我使用
clsx
和TextField
来添加条件样式。
export const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
// ...
},
valid: {
"& fieldset": {
borderColor: theme.palette.success.main,
borderWidth: 2
}
}
})
);
const classes = useStyles();
<TextField
{...props}
className={clsx(classes.root, { [classes.valid]: isValid })}
/>
I'm trying to find a similar approach in MUI v5.我试图在 MUI v5 中找到类似的方法。 Is there any alternative for conditional styles in MUI v5 other than with
clsx
and makestyles
.除了
clsx
和makestyles
之外,MUI v5 中的条件样式是否有任何替代方法。
Let me know if more information is required.如果需要更多信息,请告诉我。
There are multiple ways to do that:有多种方法可以做到这一点:
Use this if you want to conditionally set a property based on a boolean value.如果要根据布尔值有条件地设置属性,请使用此选项。
const Box1 = styled(Box, {
shouldForwardProp: (prop) => prop !== "showBorder"
})(({ showBorder }) => ({
border: showBorder ? "solid red 5px" : "none"
}));
<Box1 />
<Box1 showBorder />
Use this if you want to conditionally set a property based on multiple values.如果您想根据多个值有条件地设置属性,请使用此选项。
import { styled, darken } from "@mui/material/styles";
const colors = {
hauntedForest: "#0b5b38",
redLust: "#b20608",
spaceExplorer: "#1244a1",
default: "#000000"
};
const Box2 = styled(Box, {
shouldForwardProp: (prop) => prop !== "variant"
})(({ variant }) => ({
backgroundColor: colors[variant] ?? colors.default,
border: "5px solid " + darken(colors[variant] ?? colors.default, 0.3)
}));
<Box2 variant="hauntedForest" />
<Box2 variant="redLust" />
<Box2 variant="spaceExplorer" />
<Box2 />
Use this if you want to conditionally set multiple properties.如果您想有条件地设置多个属性,请使用此选项。
const Box3 = styled(Box, {
shouldForwardProp: (prop) => prop !== "isFancy" && prop !== "isFancyBorder"
})(({ theme, isFancy, isFancyBorder }) => ({
...(isFancy && {
borderRadius: theme.shape.borderRadius,
boxShadow: "0 4px 6px gray, 0 1px 3px rgba(0, 0, 0, 0.08)",
backgroundImage: "linear-gradient(90deg, #be5af7, #165b91)"
}),
...(isFancyBorder && {
backgroundColor: "transparent",
border: "5px solid transparent",
borderImage: "linear-gradient(90deg, #be5af7, #165b91)",
borderImageSlice: 1
})
}));
<Box3 isFancy />
<Box3 isFancyBorder />
All of the methods above can also be applied when using sx
props since they use JS object to describe the styles.上述所有方法也可以在使用
sx
道具时应用,因为它们使用 JS 对象来描述样式。
This seem to work for me这似乎对我有用
Using sx使用 sx
sx={{ px: variable ? 8 : null }}
sx with breakpoint带断点的 sx
sx={{ px: { md: variable ? 8 : null } }}
prop支柱
<Typography align={variable ? 'center' : 'inherit'}>
Using className使用类名
className={ variable ||'class-name'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.