React TypeScript中CSS文字波浪动画无法生效,求问题排查
解决React TypeScript中文字波浪动画的问题
你的代码存在以下几个核心问题:
- 拼写错误:引用容器样式时写了
styles.waiviy,但定义的是styles.waviy,字母拼写错误导致样式完全不生效。 - MUI sx属性限制:sx不支持嵌套选择器(如
waviy span)和@keyframes定义,这类样式无法通过sx直接作用到子元素。 - CSS变量--i的类型问题:TypeScript中内联样式使用自定义属性时,必须用字符串形式的键(如
{'--i': 0}),直接写--i:0会触发类型报错。 - 关键帧动画定义方式错误:内联样式无法声明
@keyframes,必须通过全局CSS或styled组件实现。
修正方案(使用MUI styled组件)
这种方式能完整保留原动画逻辑,同时适配React TypeScript环境:
import React from 'react'; import Typography from '@mui/material/Typography'; import { styled } from '@mui/material/styles'; // 创建带波浪动画的自定义容器组件 const WaviyText = styled('div')` position: relative; -webkit-box-reflect: below -20px linear-gradient(transparent, rgba(0,0,0,.2)); font-size: 60px; span { font-family: 'Alfa Slab One', cursive; position: relative; display: inline-block; text-transform: uppercase; color: #fbbf2c; animation: waviy 1s infinite; animation-delay: calc(.1s * var(--i)); } @keyframes waviy { 0%,40%,100% { transform: translateY(0); } 20% { transform: translateY(-20px); } } `; function App() { return ( <Typography variant={'h3'} fontWeight={'bold'}> All Your <WaviyText> <span style={{ '--i': 0 } as React.CSSProperties}>p</span> <span style={{ '--i': 1 } as React.CSSProperties}>l</span> <span style={{ '--i': 2 } as React.CSSProperties}>a</span> <span style={{ '--i': 3 } as React.CSSProperties}>n</span> <span style={{ '--i': 4 } as React.CSSProperties}>t</span> <span style={{ '--i': 5 } as React.CSSProperties}>s</span> </WaviyText> in One Place </Typography> ); } export default App;
关键修正说明:
- 用MUI的
styled创建自定义组件,支持完整的CSS语法(嵌套选择器、keyframes)。 - 每个span的内联样式通过
{'--i': n}定义CSS变量,并用as React.CSSProperties规避TypeScript类型检查报错。 - 修正了容器样式的拼写错误,确保样式正常挂载。
替代方案(使用全局CSS)
如果不想用styled组件,可以创建全局CSS文件实现动画:
/* App.css */ .waviy { position: relative; -webkit-box-reflect: below -20px linear-gradient(transparent, rgba(0,0,0,.2)); font-size: 60px; } .waviy span { font-family: 'Alfa Slab One', cursive; position: relative; display: inline-block; text-transform: uppercase; color: #fbbf2c; animation: waviy 1s infinite; animation-delay: calc(.1s * var(--i)); } @keyframes waviy { 0%,40%,100% { transform: translateY(0); } 20% { transform: translateY(-20px); } }
组件中引用:
import React from 'react'; import Typography from '@mui/material/Typography'; import './App.css'; function App() { return ( <Typography variant={'h3'} fontWeight={'bold'}> All Your <div className="waviy"> <span style={{ '--i': 0 } as React.CSSProperties}>p</span> <span style={{ '--i': 1 } as React.CSSProperties}>l</span> <span style={{ '--i': 2 } as React.CSSProperties}>a</span> <span style={{ '--i': 3 } as React.CSSProperties}>n</span> <span style={{ '--i': 4 } as React.CSSProperties}>t</span> <span style={{ '--i': 5 } as React.CSSProperties}>s</span> </div> in One Place </Typography> ); } export default App;
内容的提问来源于stack exchange,提问作者user18943198
相关产品推荐
相关产品推荐

