给定css
.App {
font-family: sans-serif;
text-align: center;
}
.App:hover {
background-color: red;
}
和JSX代码
import "./styles.css";
import { useRef } from "react";
export default function App() {
const r = useRef();
const handleClick = () => {
console.log(r.current.style.backgroundColor);
};
return (
<div className="App" ref={r} onClick={handleClick}>
something
</div>
);
}
看到codesandbox我想要得到div的活动背景色(它是红色)。但是代码什么也没给我。正确的做法是什么?
.style
只告诉您元素的行内样式,而这个div没有行内样式。如果你想知道内联样式和css选择器组合后的样式,你需要getComputedStyle
const handleClick = () => {
console.log(window.getComputedStyle(r.current).backgroundColor);
}
el.style.X
不能正常工作。相反,使用window.getComputedStyle(el),你可以获得样式的完整列表。作为一个例子,你可以看到它。