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

如何在React中获取元素ID以用于querySelector?

如何正确选中该React中的input元素

你的input的ID是通过CSS Modules的styles["date"]生成的动态值,所以不能直接写静态的#date,要把这个动态ID传入querySelector,写法如下:

const dateElement = document.querySelector(`#${styles["date"]}`);

原因说明

CSS Modules会给类名、ID自动生成唯一的哈希后缀(比如date_abc123),用来避免全局样式冲突。所以你写在JSX里的id={styles["date"]},最终渲染到页面上的ID是编译后的动态值,必须通过styles["date"]拿到这个真实值,才能用querySelector选中。

更优的React方案

在React里不推荐直接用document.querySelector操作DOM,更规范的方式是用useRef钩子:

import { useRef } from 'react';

// 组件内部定义ref
const dateInputRef = useRef(null);

// 在input上绑定ref
<input 
  className={styles["form-input"]} 
  type="date" 
  name="date" 
  id={styles["date"]} 
  value={date}
  ref={dateInputRef}
/>

// 获取元素
const dateElement = dateInputRef.current;

这种方式不需要依赖ID,完全遵循React的组件模型,也更稳定可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:05:23