You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为MUI主题添加自定义动画属性以实现全局复用?

实现集中管理动画值并在主题中复用

步骤1:定义动画关键帧(可选,若需自定义动画效果)

如果你的beat动画是自定义关键帧,先通过keyframes工具定义:

import { keyframes } from '@mui/material/styles';

const beat = keyframes`
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
`;

步骤2:在主题中添加集中管理的动画配置

在useAppTheme的主题对象里新增自定义字段,把动画相关的参数或完整规则存进去:

const useAppTheme = () => {
  const lightTheme = createTheme({
    palette: {
      mode: 'light',
      primary: {
        main: mainTextColor,
        contrastText: contrastTextColor,
      },
    },
    breakpoints: breakpointsOverrides,
    components: sharedComponentsOverrides,
    // 新增动画配置,按需选择拆分参数或直接存完整规则
    animations: {
      // 方式1:拆分参数,方便后续单独调整
      beat: {
        keyframe: beat,
        duration: '3s',
        iterationCount: 'infinite',
      },
      // 方式2:直接存完整动画字符串,更简洁
      // beat: 'beat 3s infinite',
    },
  });

  return lightTheme;
};

步骤3:在Styled组件中从主题读取动画

在组件里直接通过theme对象获取预定义的动画配置:

// 对应方式1:拆分参数的写法
const StyleNetworkIcon = styled(SignalWifiOff)(({ theme }) => ({
  animation: `${theme.animations.beat.keyframe} ${theme.animations.beat.duration} ${theme.animations.beat.iterationCount}`,
  fontSize: 30,
  '&:hover': {
    opacity: 1,
  },
}));

// 对应方式2:完整字符串的写法
// const StyleNetworkIcon = styled(SignalWifiOff)(({ theme }) => ({
//   animation: theme.animations.beat,
//   fontSize: 30,
//   '&:hover': {
//     opacity: 1,
//   },
// }));

补充说明

  • 确保你的useAppTheme返回的主题通过ThemeProvider全局注入,这样所有子组件都能访问到theme.animations。
  • 这种集中管理的方式可以避免重复硬写动画参数,后期修改时只需调整主题配置即可全局生效。

内容的提问来源于stack exchange,提问作者Richardson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 06:11:01