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

React函数组件中如何获取指定className的所有DOM元素

React函数组件获取同className DOM元素的方案

ReactDOM.findDOMNode 本身不支持函数组件,你可以用以下两种方案实现需求:

方案1:父容器ref + 选择器查询

如果目标类名元素都在同一个父容器范围内,优先用这个方案:

  1. 用useRef创建容器ref,绑定到目标范围的最外层父元素上
  2. 在useEffect中通过父容器ref调用DOM查询方法获取目标元素

示例代码:

import { useRef, useEffect } from 'react';

function DemoComponent() {
  const containerRef = useRef(null);

  useEffect(() => {
    if (!containerRef.current) return;
    // 获取所有类名为snap的元素
    const snapElements = containerRef.current.querySelectorAll('.snap');
    // 此处写你的元素操作逻辑
    console.log(snapElements);
  }, []);

  return (
    <div ref={containerRef}>
      <div className="snap">元素1</div>
      <div className="other">非目标元素</div>
      <div className="snap">元素2</div>
    </div>
  );
}

方案2:ref回调收集元素

如果目标类名元素分散在组件不同位置,或者元素会动态增删,用ref回调的方式更稳定:

import { useRef, useEffect } from 'react';

function DemoComponent() {
  const snapRefs = useRef([]);

  useEffect(() => {
    // snapRefs.current 即为所有类名为snap的DOM元素集合
    console.log(snapRefs.current);
  }, []);

  return (
    <div>
      <div className="snap" ref={el => el && !snapRefs.current.includes(el) && snapRefs.current.push(el)}>元素1</div>
      <div className="other">非目标元素</div>
      <div className="snap" ref={el => el && !snapRefs.current.includes(el) && snapRefs.current.push(el)}>元素2</div>
      <div>
        <div className="snap" ref={el => el && !snapRefs.current.includes(el) && snapRefs.current.push(el)}>嵌套的目标元素</div>
      </div>
    </div>
  );
}

注意事项

  • 不推荐直接用document.getElementsByClassName('snap')全局查询,会拿到其他组件渲染的同类名元素,破坏组件封装性
  • 所有DOM操作都要放在useEffect回调中执行,确保组件挂载完成、ref已经绑定到真实DOM上,避免空值报错
  • 如果目标元素会动态增删,建议在useEffect的依赖项中添加影响元素渲染的状态变量,确保每次元素更新后你都能拿到最新的集合

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:06:07