【问题标题】:How to use conditional styles with MUI v5 using emotion styled如何使用带有情感样式的 MUI v5 使用条件样式
【发布时间】:2021-11-13 06:02:54
【问题描述】:

我正在从 MUI v4 迁移到 v5。在 v4 中,我使用 clsxTextField 添加条件样式。

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 })}
/>

我试图在 MUI v5 中找到类似的方法。除了clsxmakestyles 之外,MUI v5 中的条件样式还有其他选择吗?

如果需要更多信息,请告诉我。

【问题讨论】:

    标签: reactjs react-hooks material-ui


    【解决方案1】:

    有多种方法可以做到这一点:

    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。 Short-circuit evaluation + 扩展运算符

    如果您想有条件地设置多个属性,请使用此选项。

    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对象来描述样式。

    现场演示

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 2022-10-05
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 2022-01-25
      • 2022-11-08
      • 2021-03-29
      • 1970-01-01
      相关资源
      最近更新 更多