如何使用 document.querySelector 选择我的 CSS 模块类?

Ant*_*ino 7 css reactjs css-modules

我希望能够styles.scrollValue使用document.querySelector()

import { useEffect } from "react";
import styles from "./Navbar.module.scss";

const Navbar = () => {
  const handleScroll = () => {
    document.querySelector(styles.scrollValue).innerHTML = scrollY;
  };
  useEffect(() => {
    document.addEventListener("scroll", handleScroll);
    return () => {
      document.removeEventListener("scroll", handleScroll);
    };
  });
  return (
    <nav className={styles.navbar}>
      <div className={styles.content}>
        <h1 className={styles.scrollValue}>0</h1>
      </div>
    </nav>
  );
};
Run Code Online (Sandbox Code Playgroud)

运行此代码我收到错误:

类型错误:document.querySelector(...) 为 null

我知道我可以向该元素添加一个全局类,执行以下操作:

className={`${styles.scrollValue} scrollValue`}
Run Code Online (Sandbox Code Playgroud)

但这会破坏使用 CSS 模块的优势。

有没有一种方法可以选择 CSS 模块类而不添加另一个类?

Lok*_*tar 13

您需要将其选择为一个类,

document.querySelector(`.${styles.scrollValue}`)
Run Code Online (Sandbox Code Playgroud)

调用styles.property返回一个如下值,

scrollValue: '_src_styles_module__scrollValue'

因此,当您调用 document.querySelector 时,它会查找_src_styles_module__scrollValue哪个没有选择器类型(例如 ).,或者#哪个使其查找匹配的元素<_src_styles_module__scrollValue>(在本例中)。由于不存在具有该名称或散列名称的元素,因此它将返回 null。

工作演示