首页 > 解决方案 > MUI sx 道具中的动态样式?

问题描述

是否可以在 MUI sx 道具中使用动态样式?像这样的东西:

<Box
  key={index}
  sx={{
    height: "100%",
    width: "100%",
    {index === imgIndex &&
    {"@keyframes fadeIn": {
        from: {
            opacity: 0,
        },
        to: {
            opacity: 1,
        },
        },
        "fade-in": {
        animation: "$fadeIn 2.5s",
        }}}
    }}
>
  {child}
</Box>

如果没有,有什么选择可以做这样的事情?

我的用例是这是对使用 MUI4(makeStyles)完成的轮播的重构,我正在迁移到 MUI5(不再使用 makeStyles)

标签: reactjsmaterial-ui

解决方案


您可以通过对属性本身而不是在对象内部设置条件来做到这一点。

这是一个示例,说明如何在单击按钮时更改框的 bgColor

import Box from "@mui/material/Box";
import Button from "@mui/material/Button";

export default function BoxSx() {
  const [clicked, setClicked] = React.useState(false);

  const handleClick = () => {
    setClicked(!clicked);
  };

  return (
    <>
      <Button onClick={handleClick}>Change</Button>
      <Box
        sx={{
          width: 300,
          height: 300,
          bgcolor: clicked ? "primary.dark" : "secondary.light",
        }}
      />
    </>
  );
}


推荐阅读