react如何获取组件根元素
获取组件根元素的方法
在React中,获取组件根DOM元素可以通过以下几种方式实现:
使用ref属性
通过createRef或useRef创建ref对象,并将其附加到组件的根元素上:
import React, { useRef, useEffect } from 'react';
function MyComponent() {
const rootRef = useRef(null);
useEffect(() => {
console.log(rootRef.current); // 获取到DOM元素
}, []);
return <div ref={rootRef}>...</div>;
}
类组件中的回调ref
在类组件中可以使用回调形式的ref:
class MyComponent extends React.Component {
setRootRef = (element) => {
this.rootElement = element;
};
componentDidMount() {
console.log(this.rootElement);
}
render() {
return <div ref={this.setRootRef}>...</div>;
}
}
通过事件对象获取
从事件处理程序中可以获取事件目标元素:
function MyComponent() {
const handleClick = (e) => {
console.log(e.currentTarget); // 事件绑定的元素
};
return <div onClick={handleClick}>...</div>;
}
使用findDOMNode(不推荐)
React提供的findDOMNode可以获取组件实例对应的DOM节点,但官方已不推荐使用:
import { findDOMNode } from 'react-dom';
class MyComponent extends React.Component {
componentDidMount() {
const node = findDOMNode(this);
console.log(node);
}
render() {
return <div>...</div>;
}
}
注意事项
- 函数组件没有实例,不能直接使用
findDOMNode - ref获取的是渲染后的实际DOM元素,组件更新时ref会同步更新
- 避免在渲染期间访问ref,因为此时DOM可能还未更新







