react中如何获取dom
获取 DOM 的方法
在 React 中,可以通过 useRef 或回调 Refs 的方式获取 DOM 节点。以下是具体实现方法:
使用 useRef Hook
useRef 是 React Hooks 提供的一种方式,可以方便地获取 DOM 节点或存储可变值。以下是示例代码:
import React, { useRef, useEffect } from 'react';
function MyComponent() {
const inputRef = useRef(null);
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
return <input ref={inputRef} type="text" />;
}
useRef 创建的 ref 对象通过 ref 属性附加到目标 DOM 节点后,可以通过 ref.current 访问该节点。
使用回调 Refs
回调 Refs 是一种更灵活的方式,允许在 ref 被设置或清除时执行自定义逻辑。以下是示例代码:
import React, { useEffect } from 'react';
function MyComponent() {
let inputRef = null;
useEffect(() => {
if (inputRef) {
inputRef.focus();
}
}, []);
return <input ref={el => inputRef = el} type="text" />;
}
回调 Refs 通过函数接收 DOM 节点作为参数,可以手动将其赋值给变量或其他逻辑处理。
类组件中的 React.createRef
在类组件中,可以通过 React.createRef 创建 ref 并附加到 DOM 节点:
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
if (this.inputRef.current) {
this.inputRef.current.focus();
}
}
render() {
return <input ref={this.inputRef} type="text" />;
}
}
注意事项
- 避免过度使用 ref 直接操作 DOM,优先考虑 React 的状态驱动机制。
ref不能用于函数组件,除非使用forwardRef转发。- 在组件卸载时,React 会自动清理
ref.current,无需手动置空。







