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

Vite.js重命名CSS类名后,如何在JS中正确使用类选择器?

问题描述

我编写了如下代码:

import styles from "../styles/dragdrop.module.css";
(...)

return ( 
        <div className={styles.dragDrop}></div>
    );

经过Vite构建项目后,代码变为:

<div class="_dragDrop_d8kak_45"></div>

(CSS类名从dragDrop变为**_dragDrop_d8kak_45**)

但我在前端JS中使用CSS选择器操作这些div元素:

const targetBox = e.target.closest(".dragDrop");

现在我的前端JS代码无法正常工作。我考虑使用div[class*="dragDrop"]这类选择器,但感觉这不是好办法。请问正确的处理方式是什么?

解决方法

1. 用模块导出的类名构建选择器

既然已经通过import styles拿到了处理后的类名,直接在JS里用这个值生成选择器即可:

const targetBox = e.target.closest(`.${styles.dragDrop}`);

不管构建后类名被哈希成什么,JS里的选择器都会自动匹配对应的类,这是CSS Modules的标准用法,彻底避免硬编码类名的问题。

2. 添加固定标识类(备用方案)

如果需要一个不会被哈希的类名用于JS选择,可以在JSX里额外加一个普通类(不要放在.module.css文件中):

return ( 
        <div className={`${styles.dragDrop} drag-drop-mark`}></div>
    );

然后JS里直接用这个固定类名:

const targetBox = e.target.closest(".drag-drop-mark");

注意这个额外的类不能写在模块化CSS文件里,否则也会被哈希处理。

3. 使用ref直接获取元素(更高效)

如果是自己渲染的元素,用React的ref(假设你使用React)直接绑定DOM节点,完全不用依赖选择器:

import { useRef } from 'react';
import styles from "../styles/dragdrop.module.css";

function YourComponent() {
  const dragDropRef = useRef(null);

  const handleEvent = () => {
    if (dragDropRef.current) {
      // 直接操作dragDropRef.current即可
    }
  };

  return ( 
        <div ref={dragDropRef} className={styles.dragDrop}></div>
    );
}

这种方式绕开了类名匹配的问题,代码更简洁可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:15:06