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

styled-components使用长格式CSS动画语法实现多关键帧动画问题

问题原因

styled-components 本身完全支持CSS原生的多动画逗号分隔语法,该问题和标签模板拼接逻辑无关,核心是你的动画声明方式错误:
你当前用css辅助函数包裹的keyframes代码返回的是一段完整的CSS规则片段,不是单纯的动画名称值,插入到animation-name属性中时,只有第一个插值会被styled-components特殊解析为可用的动画标识,第二个插值会被识别为无效值截断,因此只有第一个动画会执行。

修复方案

你需要使用styled-components提供的keyframesAPI声明动画,其返回值是可以直接插入到animation相关属性中的动画标识,多动画场景下直接按逗号分隔插入即可正常运行:

import { styled, keyframes } from 'styled-components'

// 示例声明两组动画,你可以根据需求声明8组不同的keyframes
const fadeIn = keyframes`
  from { opacity: 0; }
  to { opacity: 1; }
`
const zoomIn = keyframes`
  from { transform: scale(1); }
  to { transform: scale(1.2); }
`

// 多动画写法示例
const AnimatedImg = styled.img`
  animation-name: ${fadeIn}, ${zoomIn};
  animation-delay: 0, 200ms;
  animation-duration: 200ms;
  animation-timing-function: linear;
  animation-iteration-count: 1;
`

如果需要动态切换动画,直接根据props返回对应的keyframes变量即可:

// 示例动态匹配你定义的8组动画映射表
const animMap = {
  fade: fadeIn,
  zoom: zoomIn,
  // 剩下6组动画配置
}

const AnimatedImg = styled.img`
  animation-name: ${props => animMap[props.firstAnim]}, ${props => animMap[props.secondAnim]};
  animation-delay: 0, 200ms;
  animation-duration: 200ms;
  animation-timing-function: linear;
  animation-iteration-count: 1;
`

内容的提问来源于stack exchange,提问作者William Martin。

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:09:03