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

React项目使用JSS编写样式时translateY未定义报错如何解决

报错原因
  • 你在JSS样式对象中直接书写transform: translateY(0.5)时,JS解析器会将translateY()识别为自定义函数调用,但代码中从未定义过名为translateY的函数,因此触发no-undef规则报错,编译终止。
  • 代码存在两个隐藏的运行时问题:
    • CSS的translateY函数参数必须带合法单位(如px、rem),仅写数字0.5浏览器无法识别,动画不会生效
    • JSX中书写SVG属性时,带连字符的属性需要转成驼峰格式,原代码里的stroke-width要改成strokeWidth,否则React会抛出属性无效警告
修复方案
  1. 所有transform属性的取值用字符串包裹,给位移值加上合法CSS单位,建议额外加transition属性让位移动画更顺滑
  2. 修正SVG属性的驼峰命名,避免React属性警告
  3. 原代码中state变量名和样式类名重名,建议改名避免变量歧义
修复后可运行代码
import { createUseStyles } from 'react-jss'
import React, { useState } from 'react';

const useStyles = createUseStyles({
    button: {
        cursor: 'pointer',
        transition: 'transform 0.2s ease',
        '&:hover': {
            transform: 'translateY(2px)' // 可根据交互需求调整位移大小,原0.5px视觉效果过弱
        }
    },
    
    clickButton: {
        background: '#b60000',
        transform: 'translateY(2px)',
        cursor: 'pointer'
    }
})

function Button() {
    const [buttonClass, toggleButton] = useState(useStyles.button);

    return (
        <div>
            <svg width="900" height="600">
                <circle cx="120" cy="120" r="150" stroke="grey" strokeWidth="3" fill="grey"/>
                <circle cx="120" cy="120" r="100" stroke="red" strokeWidth="3" fill="red" className={buttonClass} onClick={() => toggleButton(useStyles.clickButton)}/>
            </svg>
        </div>
    )
}

export default Button

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 18:57:33