react如何获取css得值
获取 CSS 值的常用方法
使用 window.getComputedStyle
通过 window.getComputedStyle 可以获取元素最终计算的样式值(包括内联样式和外部样式表)。以下是一个示例代码:
const element = document.getElementById('target-element');
const computedStyle = window.getComputedStyle(element);
const width = computedStyle.getPropertyValue('width');
console.log(width); // 输出元素的宽度值
通过 style 属性获取内联样式
如果样式是直接以内联方式(通过 style 属性)设置的,可以通过元素的 style 属性直接访问:

const element = document.getElementById('target-element');
const inlineColor = element.style.color; // 仅获取内联样式
console.log(inlineColor);
使用 ref 和 currentStyle(旧版 IE 兼容)
对于旧版 IE 浏览器,可以使用 currentStyle 替代 getComputedStyle:

const element = document.getElementById('target-element');
const style = element.currentStyle || window.getComputedStyle(element);
const fontSize = style.fontSize;
console.log(fontSize);
在 React 中结合 useRef 获取样式
通过 useRef 获取 DOM 节点后,再调用 getComputedStyle:
import React, { useRef, useEffect } from 'react';
function Component() {
const ref = useRef(null);
useEffect(() => {
if (ref.current) {
const style = window.getComputedStyle(ref.current);
const height = style.getPropertyValue('height');
console.log(height);
}
}, []);
return <div ref={ref}>目标元素</div>;
}
通过 CSS 变量动态获取值
如果样式通过 CSS 变量(Custom Properties)定义,可以通过 getPropertyValue 获取:
const element = document.getElementById('target-element');
const computedStyle = window.getComputedStyle(element);
const primaryColor = computedStyle.getPropertyValue('--primary-color');
console.log(primaryColor); // 输出 CSS 变量值
注意事项
getComputedStyle返回的值是只读的,无法直接修改。- 内联样式(
element.style)仅能获取通过style属性直接设置的样式,无法获取外部样式表中的值。 - 返回的值可能带有单位(如
px、%),需根据实际需求处理。






