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

React使用styled-components创建动态时钟报组件动态生成警告如何解决

问题原因

你当前所有styled样式组件、keyframes动画的定义都放在了Clock函数组件内部,React每渲染一次Clock组件,都会重新创建一套新的样式组件实例,不符合styled-components的使用规则,因此触发该警告。

解决方案

将所有样式、动画定义移到组件外部,动态值全部通过props传递计算即可,修改后的完整Clock组件代码如下:

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

// 外部预定义时钟容器样式
const StyledClock = styled.div`
  width: 10vh;
`

// 外部预定义小时针动画,动态角度值从props读取计算
const animationHour = keyframes`
  from {
    transform: rotate(${props => props.hourDegrees}deg);
  }
  to {
    transform: rotate(${props => props.hourDegrees + 360}deg);
  }
`
const HourStyled = styled.div`
  animation: ${animationHour} 4s ease-out infinite;
`

// 外部预定义分针动画
const animationMinute = keyframes`
  from {
    transform: rotate(${props => props.minuteDegrees}deg);
  }
  to {
    transform: rotate(${props => props.minuteDegrees + 360}deg);
  }
`
const MinuteStyled = styled.div`
  animation: ${animationMinute} 4s ease-out infinite;
`

export default function Clock ({ minuteDegrees, hourDegrees, index}) { 
  return(
    <StyledClock className={index}>
      <HourStyled className={hourDegrees} hourDegrees={hourDegrees}/>
      <MinuteStyled className={minuteDegrees} minuteDegrees={minuteDegrees}/>
    </StyledClock>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 22:30:01