之前我们已经讲过了如何获取类组件实例,那么如何获取函数组件的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
最后,我们来看一下运行结果:

感谢您的观看,我们下次再见!
文章不错支持一下,非常喜欢
文章不错非常喜欢,支持一下
友链已经添加好了,欢迎回访哈
文章不错支持一下,非常喜欢
文章不错非常喜欢,支持一下
文章不错支持一下,非常喜欢
文章不错非常喜欢,支持一下
马克吐温的作品就很经典,小时候很爱看
文章不错支持一下,非常喜欢
文章不错非常喜欢,支持