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

如何在不使用findDomNode的情况下通过React ref操作get/setPropertyValue

解决方案

你错误地直接在DOM元素上调用了getPropertyValue和setProperty方法——这两个方法属于CSSStyleDeclaration对象,而非DOM元素本身。要调用这两个方法,你需要访问DOM元素的style属性(对应元素的内联样式对象)。

修正后的toggleColor代码

const toggleColor = () => {
  const el = buttonRef.current;
  // 访问元素的style属性,调用对应的方法
  const currentColor = el.style.getPropertyValue('--buttonColor');
  
  // 示例:修改CSS变量值
  el.style.setProperty('--buttonColor', '#ff0000');
};

补充说明

  • 你的ref绑定代码是正确的,buttonRef.current确实指向button的底层DOM元素,问题仅在于调用方法的对象错误。
  • 如果--buttonColor是在外部样式表中定义的,el.style.getPropertyValue会返回空字符串(因为它只读取内联样式)。但你可以直接通过el.style.setProperty设置变量值,内联设置会覆盖样式表中的定义,满足你无需使用getComputedStyle的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:56:03