代码之家  ›  专栏  ›  技术社区  ›  william007

使用useRef获取活动背景色

  •  1
  • william007  · 技术社区  · 2 年前

    给定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的活动背景色(红色)。但密码什么也没给我。正确的方法是什么?

    2 回复  |  直到 2 年前
        1
  •  1
  •   Nicholas Tower    2 年前

    .style 只告诉您元素上的内联样式,而此div没有内联样式。如果您想知道在组合内联样式和css选择器时产生的样式,您需要 getComputedStyle

    const handleClick = () => {
      console.log(window.getComputedStyle(r.current).backgroundColor);
    }
    
        2
  •  0
  •   Veyis Aliyev    2 年前

    el.style.X 工作不正常。代替此用途 window.getComputedStyle(el) 你可以得到完整的样式列表。作为 example 你可以看到它。