之前我们已经讲过了如何获取类组件实例,那么如何获取函数组件的DOM呢?
原理
我们可以通过forwardRef将函数组件转化为类组件,然后通过createRef创建ref引用对象,最后将ref引用对象传递给函数组件。
案例代码
import React,{PureComponent,createRef,forwardRef} from "react";
const HelloWorld = forwardRef(function(props,ref){
return (
<div>
<h1 ref={ref}>Hello World</h1>
<p>哈哈哈</p>
</div>
)
})
export class App extends PureComponent{
constructor(){
super()
this.hwRef = createRef()
}
getComponent(){
console.log(this.hwRef.current)
}
render(){
return (
<div>
<HelloWorld ref={this.hwRef}></HelloWorld>
<button onClick={e=>this.getComponent()}>获取组件实例</button>
</div>
)
}
}
export default App注意事项
- 函数组件必须使用
forwardRef进行转化 - 函数组件必须使用
ref接收ref引用对象 - 函数组件必须使用
current获取DOM
最后,我们来看一下运行结果:

感谢您的观看,我们下次再见!
我热爱 旅游专栏。令人惊艳了解路线。
欣赏你的照片, 我明白, 世界很美。感谢 旅行灵感。
读起来像小说。继续保持 带来的灵感。
让人精神焕发的 帖子! 我准备订票了。
以后焦虑了或者迷茫了记得回来看看
我非常喜欢 出行博客。鼓舞人心查看路线。
你们的博客 百分百 帮助选择路线。坚持!
信息丰富的 出行资源! 越来越棒!
My brother suggested I might like this blog. He was entirely right. This post actually made my day. You cann't imagine just how much time I had spent for this information! Thanks!
我热爱, 写得很实在。你的博客 就是 最好的例子。很出色。