有多种方法可以做到这一点:
1. 条件运算符
如果您想根据布尔值有条件地设置属性,请使用此选项。
const Box1 = styled(Box, {
shouldForwardProp: (prop) => prop !== "showBorder"
})(({ showBorder }) => ({
border: showBorder ? "solid red 5px" : "none"
}));
<Box1 />
<Box1 showBorder />
2. 词典
如果您想根据多个值有条件地设置属性,请使用此选项。
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 />
3. 短路评估+ 扩展运算符
如果您想有条件地设置多个属性,请使用此选项。
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 />
使用时也可以应用上述所有方法sx props因为他们使用JS对象来描述样式。
现场演示