已经学会了使用 CSS 中的动画@keyframe。但是我想为我的 React 项目编写自定义动画代码(使用 Material UI)。我的挑战是如何编写 Javascript 代码来使用makeStyle()Material UI 自定义我的动画。
@keyframe
makeStyle()
这次我希望能够在 Material UI 中自定义百分比的过渡过程。我需要编写这样的代码,makeStyle()但我不知道如何:
@keyframes myEffect { 0%{ opacity:0; transform: translateY(-200%); } 100% { opacity:1; transform: translateY(0); } }
下面是一个演示keyframes语法的示例makeStyles:
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);
对于那些已经开始使用 Material-UI v5 并想知道如何使用 Emotion 而不是 来做到这一点的人来说makeStyles,下面是使用 Emotion 实现等效样式的一种方法的示例。
/** @jsxImportSource @emotion/react */ import React from "react"; import ReactDOM from "react-dom"; import { css, keyframes } from "@emotion/react"; import { useTheme } from "@mui/material/styles"; import Button from "@mui/material/Button"; const myEffect = keyframes` 0% { opacity: 0; transform: translateY(-200%); } 100% { opacity: 1; transform: translateY(0); } `; const myEffectExit = keyframes` 0% { opacity: 1; transform: translateY(0); } 100% { opacity: 0; transform: translateY(-200%); } `; function App() { const theme = useTheme(); const animatedItem = css` animation: ${myEffect} 3000ms ${theme.transitions.easing.easeInOut}; `; const animatedItemExiting = css` animation: ${myEffectExit} 3000ms ${theme.transitions.easing.easeInOut}; opacity: 0; transform: translateY(-200%); `; const [exit, setExit] = React.useState(false); return ( <> <div css={exit ? animatedItemExiting : animatedItem}> <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);