当角色限制反应为100时,添加抖动动画



我有一个组件有一个限制,字符限制,如果用户达到限制,组件就会抖动,这是预期的结果,但在我当前的代码中什么都没有发生。

const useStyles = makeStyles(() => ({
shake:{
animation: 'description 0.5s',
animationIterationCount: '1',
},
'@keyframes description':{
'0%': { transform: 'translate(0)' },
'15%': { transform: 'translate(-4px, 0)' },
'30%': { transform: 'translate(6px, 0)' },
'45%': { transform: 'translate(-4px, 0)' },
'60%': { transform: 'translate(6px, 0)' },
'100%': { transform: 'translate(0)' },
},
}));
const StudentAdd = ({ setOpenAlertStudent }) => {
const classes = useStyles();
const CHARACTER_LIMIT = 100;
const [isShake, setShake] = useState(false)
const onHandleChangeInputDescription = (field, value) => {
if(value.length === 100){
setShake(true)
}
......
<TextArea
label="Description (optional)"
inputProps={{
maxLength: CHARACTER_LIMIT,
}}
values={getStringDescription.name}
onChange={(value) =>
onHandleChangeInputDescription('description', value)
}
helperText={`${getStringDescription.length}/${CHARACTER_LIMIT}`}
className={
isShake
? classes.shake
: null
}
id="description"
//id={isShake === true ? classes.shake : 'description'}
/>
......

这是codesandbox 上的示例代码

https://codesandbox.io/s/lucid-banach-o6sc1j?file=/src/App.js:1081-1089

import React, { useState, useContext } from "react";
import "./styles.css";
import { makeStyles } from "@mui/styles";
import { TextField } from "@mui/material";
const useStyles = makeStyles(() => ({
shake: {
animation: "$description 15s",
animationIterationCount: "1"
},
"@keyframes description": {
"0%": { opacity: 0, transform: "translateY(0)" },
"15%": { transform: "translateY(-4px, 0)" },
"30%": { transform: "translateY(6px, 0)" },
"45%": { transform: "translateY(-4px, 0)" },
"60%": { transform: "translateY(6px, 0)" },
"100%": { opacity: 1, transform: "translateY(0)" }
}
}));
export default function App() {
const classes = useStyles();
console.log(classes.shake);
const CHARACTER_LIMIT = 100;
const [isShake, setShake] = useState(false);
const [getStringDescription, setStringDescription] = useState({
length: 0,
value: ""
});
const onHandleChangeInputDescription = (field, value) => {
if (value.target.value.length === 100) {
setShake(true);
}
setStringDescription({
length: value.target.value.length,
value: value.target.value
});
};
return (
<div className="App">
<TextField
label="Description"
inputProps={{
maxLength: CHARACTER_LIMIT
}}
values={getStringDescription.name}
onChange={(value) =>
onHandleChangeInputDescription("description", value)
}
helperText={`${getStringDescription.length}/${CHARACTER_LIMIT}`}
sx={{
"& .MuiInputBase-input.MuiInputBase-inputMultiline": {
height: "100px !important"
},
"& .MuiTextField-root > .MuiOutlinedInput-root": {
padding: "8.5px 14px"
}
}}
id="description"
className={isShake ? classes.shake : null}
/>
</div>
);
}

  1. 如果抖动动画代码不起作用,请更改所需动画的关键帧
  2. 在100个字符后,将添加动画类。但一旦添加,您可能需要删除该类,以便在角色为100时再次显示动画

参考:https://stackoverflow.com/questions/58948890/how-to-apply-custom-animation-effect-keyframes-in-mui[1]

相关内容

最新更新