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

TypeScript结合Emotion Styled-components组件动态样式不生效求助

问题原因

  1. 动画插值函数未正确解构props
    你第一种写法中的插值函数参数写为(open) =>,这里拿到的实际是完整的props对象,而非props下的open属性,对象转布尔值恒为true,导致条件判断永远命中展开分支,无法根据状态切换动画。
  2. 缺少animation-fill-mode: forwards配置
    CSS动画默认执行完成后会回弹到元素的初始样式,未指定forwards属性的话,动画结束后高度不会保持在关键帧的最终状态,看起来就像动画没有生效。
  3. 第二种写法缺少收起状态的动画配置
    你第二种写法仅在open=true时定义了动画属性,open=false时没有对应的收起动画规则,自然无法触发收起效果。

修正后的代码

import { keyframes } from '@emotion/react'
import styled from '@emotion/styled/macro'

const expandAnimation = keyframes`
  0% {
    height: 180px;
  }
  100% {
    height: 240px;
  }
`

const unexpandAnimation = keyframes`
  0% {
    height: 240px;
  }
  100% {
    height: 180px;
  }
`

export const CardWrapper = styled.div<{open: boolean}>`
  /* 设置初始高度和动画公共配置 */
  height: 180px;
  animation-duration: 1s;
  animation-timing-function: ease-in-out;
  animation-fill-mode: forwards;
  /* 根据open属性动态切换动画名 */
  animation-name: ${({ open }) => open ? expandAnimation : unexpandAnimation};
`

如果不需要首次渲染时触发动画,可以改用CSS transition实现,逻辑更简洁:

export const CardWrapper = styled.div<{open: boolean}>`
  height: ${({ open }) => open ? '240px' : '180px'};
  transition: height 1s ease-in-out;
`

内容的提问来源于stack exchange,提问作者PandaMastr
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:24:04