当前位置:首页 > React

react 如何获取dom

2026-03-30 19:01:42React

获取 DOM 的方法

在 React 中,可以通过 ref 获取 DOM 元素。ref 提供了一种直接访问 DOM 节点或 React 元素的方式。

使用 useRef Hook(函数组件)

import React, { useRef, useEffect } from 'react';

function MyComponent() {
  const myRef = useRef(null);

  useEffect(() => {
    if (myRef.current) {
      console.log(myRef.current); // 访问 DOM 节点
      myRef.current.focus(); // 示例:聚焦输入框
    }
  }, []);

  return <input ref={myRef} type="text" />;
}

使用 createRef(类组件)

import React, { Component, createRef } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.myRef = createRef();
  }

  componentDidMount() {
    if (this.myRef.current) {
      console.log(this.myRef.current); // 访问 DOM 节点
      this.myRef.current.focus(); // 示例:聚焦输入框
    }
  }

  render() {
    return <input ref={this.myRef} type="text" />;
  }
}

回调 Refs

另一种方式是使用回调函数形式的 ref,适用于需要更精细控制的情况。

function MyComponent() {
  let myRef = null;

  const setRef = (element) => {
    myRef = element;
    if (myRef) {
      console.log(myRef); // 访问 DOM 节点
    }
  };

  return <input ref={setRef} type="text" />;
}

转发 Refs

如果需要将 ref 传递给子组件,可以使用 forwardRef

const ChildComponent = React.forwardRef((props, ref) => {
  return <input ref={ref} type="text" />;
});

function ParentComponent() {
  const inputRef = useRef(null);

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  return <ChildComponent ref={inputRef} />;
}

获取多个 DOM 元素

通过回调 Refs 或动态生成 ref 可以获取多个 DOM 元素。

react 如何获取dom

function MyComponent() {
  const itemsRef = useRef({});

  useEffect(() => {
    Object.values(itemsRef.current).forEach((el) => {
      if (el) console.log(el);
    });
  }, []);

  return (
    <div>
      {[1, 2, 3].map((item) => (
        <div key={item} ref={(el) => (itemsRef.current[item] = el)}>
          Item {item}
        </div>
      ))}
    </div>
  );
}

注意事项

  • ref 在组件挂载时才会被赋值,卸载时变为 null,使用时需检查 current 是否存在。
  • 避免过度使用 ref,优先考虑 React 的状态和 props 管理。

标签: reactdom
分享给朋友:

相关文章

react中monent如何获取日期

react中monent如何获取日期

使用 Moment.js 获取当前日期 在 React 中通过 Moment.js 获取当前日期,可以直接调用 moment() 函数。它会返回包含当前日期和时间的 Moment 对象。 impor…

react性能如何

react性能如何

React 性能特点 React 通过虚拟 DOM(Virtual DOM)和高效的 diff 算法优化性能。虚拟 DOM 减少了直接操作真实 DOM 的开销,仅在必要时更新变化的部分。React 的…

react 如何分页

react 如何分页

分页实现方法 在React中实现分页功能可以通过多种方式完成,具体取决于数据来源(如API或本地数据)和UI库的选择。以下是常见的实现方法: 使用本地数据分页 对于存储在组件状态或Context中…

react 如何运行

react 如何运行

运行 React 项目的步骤 安装 Node.js 确保系统已安装 Node.js(建议版本 16+),可通过官网下载并安装。安装后验证版本: node -v npm -v 创建 React 项目…

react如何发布

react如何发布

发布React应用的步骤 构建生产版本 使用以下命令生成优化后的生产版本代码,代码会被压缩并移除开发环境中的调试工具: npm run build 构建完成后会生成build文件夹,包含所有静态资源…

如何调试react

如何调试react

调试 React 应用的方法 使用 React Developer Tools 安装浏览器扩展(Chrome/Firefox),通过组件树查看组件状态、props 和 hooks。支持实时编辑 pro…