react里面如何获取
获取 DOM 元素的方法
在 React 中获取 DOM 元素通常使用 ref。以下是几种常见方式:
使用 useRef Hook(函数组件)
import React, { useRef, useEffect } from 'react';
function MyComponent() {
const myRef = useRef(null);
useEffect(() => {
console.log(myRef.current); // 获取到的 DOM 元素
}, []);
return <div ref={myRef}>Content</div>;
}
使用 createRef(类组件)

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
console.log(this.myRef.current); // 获取到的 DOM 元素
}
render() {
return <div ref={this.myRef}>Content</div>;
}
}
获取子组件实例
通过 ref 可以获取子组件的实例(仅适用于类组件):
class Child extends React.Component {
method() {
console.log('Child method');
}
render() { return <div>Child</div>; }
}
class Parent extends React.Component {
childRef = React.createRef();
componentDidMount() {
this.childRef.current.method(); // 调用子组件方法
}
render() {
return <Child ref={this.childRef} />;
}
}
回调形式的 ref
适用于需要更精细控制的情况:

function MyComponent() {
const setDivRef = (element) => {
console.log(element); // DOM 元素
};
return <div ref={setDivRef}>Content</div>;
}
转发 ref(Forwarding Refs)
当需要获取子组件内部的 DOM 时:
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="fancy">
{props.children}
</button>
));
function App() {
const ref = useRef();
useEffect(() => {
console.log(ref.current); // 获取到的是 <button> 元素
}, []);
return <FancyButton ref={ref}>Click</FancyButton>;
}
获取多个元素
使用 ref 回调收集多个元素:
function ItemList() {
const itemsRef = useRef([]);
useEffect(() => {
console.log(itemsRef.current); // 所有 li 元素的数组
}, []);
return (
<ul>
{[1, 2, 3].map((item, i) => (
<li key={item} ref={el => itemsRef.current[i] = el}>
Item {item}
</li>
))}
</ul>
);
}
注意事项
- 函数组件没有实例,不能直接使用 ref 获取
- 避免过度使用 ref,优先考虑 React 的数据流
- ref 会在组件挂载时赋值,卸载时变为 null
- 在函数组件中,ref 内容变化不会触发重新渲染






