Emotion Styled Component中CSS Transition不生效问题求助
问题修复方案
你的Styled Components过渡不生效,大概率是条件样式的解析方式导致浏览器未识别到属性的连续变化。以下是两种可行的修复方式:
方案一:直接通过Props计算属性值
放弃类切换的方式,将width和背景色的取值直接通过props判断,让属性值随状态平滑变更:
const Bar = styled.div<{ selected: boolean }>` width: ${({ selected }) => selected ? '40px' : '28px'}; height: 6px; cursor: pointer; border-radius: 8px; background-color: ${({ selected }) => selected ? '#fff' : '#ffffff66'}; transition: width 1s ease; `;
这种写法让浏览器能清晰捕捉到属性的数值变化,自然触发过渡动画。
方案二:用css Helper包裹条件样式
在Styled Components的条件插值中使用css工具函数包裹样式块,确保样式被正确解析(你的原生写法生效正是因为依赖了这个helper):
import { css, styled } from 'styled-components'; const Bar = styled.div<{ selected: boolean }>` width: 28px; height: 6px; cursor: pointer; border-radius: 8px; background-color: #ffffff66; transition: width 1s ease; ${({ selected }) => selected && css` width: 40px; background-color: #fff; `} `;
额外检查:确保selected状态变化时,组件没有被卸载重建(比如不要修改组件的key属性),否则元素重新创建会直接打断过渡动画。
内容的提问来源于stack exchange,提问作者user16223807
相关产品推荐
相关产品推荐

