当前位置:首页 > React

react 如何获取dom

2026-03-30 19:01:42React

获取 DOM 的方法

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

使用 useRef Hook(函数组件)

react 如何获取dom

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,适用于需要更精细控制的情况。

react 如何获取dom

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 元素。

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如何取消渲染

react如何取消渲染

取消渲染的方法 在React中,取消渲染通常指的是在某些条件下阻止组件渲染或中断正在进行的渲染过程。以下是几种常见的方法: 条件渲染 通过条件判断决定是否渲染组件或部分内容。可以使用if语句或三元运…

react如何衰减

react如何衰减

React 中的动画衰减效果实现 在 React 中实现衰减效果(如滚动衰减、拖动释放后的惯性滑动)通常需要结合物理动画原理或第三方动画库。以下是几种常见方法: 使用 CSS 动画和 @keyfra…

react如何部署

react如何部署

部署 React 应用的常见方法 使用静态服务器部署 React 应用在构建后会生成静态文件,可以直接通过静态服务器部署。常用的静态服务器包括 Nginx、Apache 等。 运行构建命令生成静态文…

理解如何react

理解如何react

理解React的核心概念 React是一个用于构建用户界面的JavaScript库,专注于通过组件化开发提高代码的可维护性和复用性。其核心思想包括虚拟DOM(Virtual DOM)和单向数据流,能够…

react如何折叠

react如何折叠

在 React 中实现折叠功能 使用 useState 管理折叠状态 通过 useState 定义一个状态变量来控制折叠面板的显示与隐藏。例如: const [isCollapsed, setIsC…

react如何实现混入

react如何实现混入

在React中实现混入(Mixin)功能可以通过以下几种方式实现,React官方已不推荐使用传统的React.createClass混入方式,但可通过高阶组件或自定义Hook替代。 高阶组件(HOC…