如何使用makestyles()在MaterialUI中应用自定义动画效果@keyframes

时间:2019-11-20 07:26:41

标签: css reactjs material-ui

我学会了使用@keyframe在CSS中使用动画。但是我想将我的自定义动画代码编写到我的React项目中(使用materialUI)。我面临的挑战是如何在MaterialUI中使用makeStyle()编写JavaScript代码以自定义动画。  我希望能够以百分比自定义过渡过程 这次在materialUI中。我需要能够在makeStyle()中编写这样的代码,但我似乎不知道该怎么做。

@keyframes myEffect {
 0%{
  opacity:0;
  transform: translateY(-200%); 
 }

100% {
  opacity:1;
  transform: translateY(0);
 }
}

2 个答案:

答案 0 :(得分:11)

在@Ryan的答案上方仅需注意一些事项。如果您使用keyframe定义makeStyles。切记在动画名称前加上$。我第一次错过了这个小细节,在下面的示例中我的代码无法正常工作

const useStyles = makeStyles({
  "@keyframes fadeIn": {
    "0%": {
      opacity: 0,
      transform: "translateY(5rem)"
    },
    "100%": {
      opacity: 1,
      transform: "translateY(0)"
    }
  },
  selector: {
    animation: "$fadeIn .2s ease-in-out"
  }
});

代替

animation: "fadeIn .2s ease-in-out"

应该是

animation: "$fadeIn .2s ease-in-out"

但是如果您在全局范围内定义keyframe。此处不需要前缀

const useStyles = makeStyles({
  "@global": {
    "@keyframes fadeIn": {
      "0%": {
        opacity: 0,
        transform: "translateY(5rem)"
      },
      "100%": {
        opacity: 1,
        transform: "translateY(0)"
      }
    }
  },
  selector: {
    animation: "fadeIn .2s ease-in-out" // --> this works
  }
});

在github上关注issue,以获取更多关于此的讨论。

答案 1 :(得分:0)

下面是一个示例,展示了keyframes中的makeStyles语法:

import React from "react";
import ReactDOM from "react-dom";

import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import clsx from "clsx";

const useStyles = makeStyles(theme => ({
  animatedItem: {
    animation: `$myEffect 3000ms ${theme.transitions.easing.easeInOut}`
  },
  animatedItemExiting: {
    animation: `$myEffectExit 3000ms ${theme.transitions.easing.easeInOut}`,
    opacity: 0,
    transform: "translateY(-200%)"
  },
  "@keyframes myEffect": {
    "0%": {
      opacity: 0,
      transform: "translateY(-200%)"
    },
    "100%": {
      opacity: 1,
      transform: "translateY(0)"
    }
  },
  "@keyframes myEffectExit": {
    "0%": {
      opacity: 1,
      transform: "translateY(0)"
    },
    "100%": {
      opacity: 0,
      transform: "translateY(-200%)"
    }
  }
}));

function App() {
  const classes = useStyles();
  const [exit, setExit] = React.useState(false);
  return (
    <>
      <div
        className={clsx(classes.animatedItem, {
          [classes.animatedItemExiting]: exit
        })}
      >
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <Button onClick={() => setExit(true)}>Click to exit</Button>
      </div>
      {exit && <Button onClick={() => setExit(false)}>Click to enter</Button>}
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit keyframes

文档:https://cssinjs.org/jss-syntax/?v=v10.0.0#keyframes-animation