react 如何获取dom
获取 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 元素。
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 管理。






